Module: Handler::ClassMethods

Defined in:
lib/handler.rb

Instance Method Summary collapse

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, options = {})
  options[:separator] ||= "_"
  options[:write_to]  ||= :handle
  options[:unique]      = true if options[:unique].nil?

  ##
  # Generate a URL-friendly name.
  #
  define_method :generate_handle do
    h = Handler.generate_handle(send(attribute), options[:separator])
    if options[: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, options[:separator])
      end
    end
    h
  end

  ##
  # Assign the generated handle to the specified attribute.
  #
  define_method :assign_handle do
    write_attribute(options[:write_to], generate_handle)
  end
end