Module: Handler::ClassMethods
- Defined in:
- lib/handler.rb
Instance Method Summary collapse
-
#handle_based_on(attribute, options = {}) ⇒ Object
Declare that a model generates a handle based on a given attribute or method.
Instance Method Details
#handle_based_on(attribute, options = {}) ⇒ Object
Declare that a model generates a handle based on a given attribute or method. Options include:
:separator - character to place between words :store - attribute in which to store handle :unique - generate a handle which is unique among all records
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
# File 'lib/handler.rb', line 97 def handle_based_on(attribute, = {}) [:separator] ||= "_" [:write_to] ||= :handle [:unique] = true if [:unique].nil? ## # Generate a URL-friendly name. # define_method :generate_handle do h = Handler.generate_handle(send(attribute), [:separator]) if [:unique] # generate a condition for finding an existing record with a # given handle find_dupe = lambda{ |h| conds = ["#{options[:write_to]} = ?", h] unless new_record? conds[0] << " AND id != ?" conds << id end conds } # increase number while *other* records exist with the same handle # (record might be saved and should keep its handle) while self.class.where(find_dupe.call(h)).size > 0 h = Handler.next_handle(h, [:separator]) end end h end ## # Assign the generated handle to the specified attribute. # define_method :assign_handle do write_attribute([:write_to], generate_handle) end end |