Skip to main content

Mobomo webinars-now on demand! | learn more.

Sometimes you want to write a batch of utility methods that can be accessed from a module for example Utility.parse_something(string) or any number of useful little tools for your application. Here’s a very clean-looking way to achieve it:

module Utilities   extend self    def parse_something(string)     # do stuff here   end    def other_utility_method(number, string)     # do some more stuff   end end

By placing "extend self" at the top of the module, you are telling it to include all of the methods defined on your module as class methods on…your module. Which means that you can now access them like other class methods! While there are other ways to do this, I think this is a very semantically clean way that gets it done quite nicely.

Update: And this is exactly why I post these Quick Tips, because sometimes there’s another solution that I hadn’t heard of! Using Ruby’s module_function you can achieve the same effect:

module Utilities   module_function      def parse_something(string)     # do stuff here   end    def other_utility_method(number, string)     # do some more stuff   end end

The module_function method either takes multiple symbols as arguments for the methods to turn into module methods or, if invoked without arguments, will cause all subsequent methods to be defined as module functions. You can read the Ruby documentation about it here. Ultimately I’m not sure which I’d go with, as module_function is pretty esoteric (I’ve never come across it in code that I’ve read), but so is extend self. It’s your call, developers!

Categories
Author

Did you know that you can use regular expressions in case statements in Ruby to check for a match? For instance, if I’m implementing some method_missing functionality and I want to check for bang or question methods, I might be tempted to do something like this:

def method_missing(name, *args)   name = name.to_s   if name.match(/!$/)     puts "Bang Method!"   elsif name.match(/?$/)     puts "Query Method?"   else     super   end end

But it’d be much cleaner if instead it looked like this:

def method_missing(name, *args)   case name.to_s     when /!$/       puts "Bang Method!"     when /?$/       puts "Query Method?"     else       super   end end

This is great, but now what if we want to call out a method for bang and question methods? Thankfully Ruby has us covered there as well:

def method_missing(name, *args)   case name.to_s     when /^(.*)!$/       bang_method($1)     when /^(.*)?$/       question_method($1)     else       super   end end

By using the $1 global variable we can access the last regular expression match performed by ruby. This is just one of those little details that makes working with Ruby such a joy.

Categories
Author

This is something that many may already use as a best practice, but if not it’s something simple and convenient to add to your repertoire. Sometimes you may have a model that requires additional information if a certain condition is met. For example, I may require a user to add more information about themselves if they wish to be listed publicly, whereas I would not if they do not wish to be listed. By combining ActiveSupport’s Object#with_options and ActiveRecord’s conditional validations, we can implement this behavior in a straightforward and readable manner (assuming here that there is a boolean field called “listed” in the database that is exposed as a checkbox or similar to the user):

class User < ActiveRecord::Base   # Our standard validations   validates_presence_of :login   validates_uniqueness_of :login    # Validations for listed users   with_options :if => :listed? do |l|     l.validates_presence_of :email     l.validates_length_of :description, :minimum => 100   end end

It’s a simple technique that piggybacks off of Rails’s automatic construction of existence query methods (in this case, listed?) for fields in the database combined with the mapping power of with_options and standard conditional validations.

Categories
Author

I love the any? and empty? convenience methods that Rails and Ruby provide, they make conditional statements much easier to read. I also really dislike the default method of checking this behavior in jQuery:

if ($('some.element').length > 0) {   // ...do something }

Well, luckily jQuery is ridiculously easy to extend, so why not just mix that functionality in with a couple of quick shot plugin methods? Just add this javascript sometime after you include jQuery:

jQuery.fn.any = function() {   return (this.length > 0); }  jQuery.fn.none = function() {   return (this.length == 0); }

That’s all you have to do! Now we can make the same call as before, but it looks a little cleaner:

if ($('some.element').any()) {   // do something more readably... }

UPDATE: Apologies, I added in the empty bit as a last-second update to the post and forgot to check and realize that empty() is part of jQuery core. Updated the name to none instead.

Categories
Author

After doing a quick Google Search I realized that everyone might not know about a great way to do URL validation in Rails. The secret is a little-known method of the URI class, regexp. It lets you generate a regular expression for matching URLs based on an array of accepted protocols. What’s even better, it can be plugged directly into Rails’s validates_format_of. It’s this easy:

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

This will match anything that URI.parse will recognize, meaning that it’s a pretty accurate and powerful URL matcher. URL validation was one of those little annoyances in writing Rails models because it really seemed like there should be an easier way. I found mine, so I thought I’d share it!

Categories
Author
1
Subscribe to Quick Tip