Module: ToParam::Base

Extended by:
ActiveSupport::Concern
Defined in:
lib/to_param/base.rb

Instance Method Summary collapse

Instance Method Details

#to_param(args) ⇒ Object

A one-liner solution for ActiveRecord::Base#to_param

Examples:

to_param :name
to_param ":id-:awesome-name"
to_param "static"


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/to_param/base.rb', line 15

def to_param(args)
    case args
    when String
      define_method "to_param" do
        args.gsub(/:(\w+)/) {|method| send(method[1..-1]).to_s.parameterize }
      end

      if args.empty?
        raise ArgumentError.new("args can not be an empty string")
      end
    when Symbol
      define_method "to_param" do
        "#{id}-#{send(args).parameterize}"
      end
    else
      raise ArgumentError.new("args can only be string or symbol")
    end
end