Skip to content

Instantly share code, notes, and snippets.

@rbmrclo
Last active August 29, 2015 13:56
Show Gist options
  • Save rbmrclo/9208681 to your computer and use it in GitHub Desktop.
Save rbmrclo/9208681 to your computer and use it in GitHub Desktop.
An simple way to find an object by slug
module Slugable
module ClassMethods
def find_by_slug(param)
if to_return = where("lower(name) LIKE ?", "#{patternify(param)}")
to_return.first
else
nil
end
end
def patternify(param)
words = param.split('-')
pattern = ''
words.each { |word| pattern << word.downcase + "_" }
words.length == 1 ? "#{words[0].downcase}%" : "#{pattern[0..-2]}%"
end
end
module InstanceMethods
def to_param
# in this case, we use the name as default field
name.downcase.gsub(/[^0-9a-zA-Z]/i,'-')
end
end
def self.included(base)
base.send :include, InstanceMethods
base.send :extend, ClassMethods
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment