Make User-Inputted Url into External Link in Rails

Make user-inputted url into external link in rails

Check this out:

validates_format_of :website, :with => URI::regexp(%w(http https))  

Source: http://intridea.com/2009/2/18/quick-tip-url-validation-in-rails?blog=company

To format a URL that is missing the protocol (http or https), I would do a before_save hook that prepends it if it's missing:

before_save :format_url

...

def format_url
self.website = "http://#{self.website}" unless self.website[/^https?/]
end

Correct User's Inputted URL - Ruby

def correct(url, protocol='http')
url = url.sub(%r{^https?://}, '')
protocol = $& || "#{protocol}://"
#url = url.chomp('/') + '/' # Uncomment to ensure the url to ends with `/`
url = 'www.' + url unless url.start_with? 'www.'
protocol + url
end

correct('www.example.com') # "http://www.example.com"
correct('www.example.com/') # "http://www.example.com/"
correct('http://www.example.com') # "http://www.example.com"
correct('example.com') # "http://www.example.com"
correct(' example.com/') # "http://www. example.com/"
correct('http://example.com') # "http://www.example.com"
correct('https://example.com') # "https://www.example.com"

Convert Jira's time tracking field format to hours

The chronic_duration gem can parse that into seconds:

ChronicDuration.parse("12w 1d 2h 5m") # => 7351500

As far as I know that format isn't a standard. ISO 8601 does include a format for durations, but that ain't it.

Dynamic Method Naming

You can do this using the send method to send a message to the class, using the parameter :define_method to tell it you are going to define a new method for that class.

For example, having a class Car

class Car
end

c = Car.new

A call to c.sound brings about the error

NoMethodError: undefined method `sound' for #<Car:0x29d9048>

But after defining the name of the method and sending it to the class:

input = "sound"

Car.send(:define_method, input) do
puts "vroom!"
end

The call to c.sound now brings the output

vroom!

Parameterize an SQL IN clause

Here's a quick-and-dirty technique I have used:

SELECT * FROM Tags
WHERE '|ruby|rails|scruffy|rubyonrails|'
LIKE '%|' + Name + '|%'

So here's the C# code:

string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" };
const string cmdText = "select * from tags where '|' + @tags + '|' like '%|' + Name + '|%'";

using (SqlCommand cmd = new SqlCommand(cmdText)) {
cmd.Parameters.AddWithValue("@tags", string.Join("|", tags);
}

Two caveats:

  • The performance is terrible. LIKE "%...%" queries are not indexed.
  • Make sure you don't have any |, blank, or null tags or this won't work

There are other ways to accomplish this that some people may consider cleaner, so please keep reading.



Related Topics



Leave a reply



Submit