Class: ActiveHash::Base

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming
Includes:
ActiveModel::Conversion
Defined in:
lib/active_hash/base.rb

Direct Known Subclasses

ActiveFile::Base

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Base

Returns a new instance of Base.



283
284
285
286
287
288
289
# File 'lib/active_hash/base.rb', line 283

def initialize(options = {})
  options.symbolize_keys!
  @attributes = options
  options.each do |key, value|
    send "#{key}=", value
  end
end

Class Attribute Details

.field_namesObject (readonly)

Returns the value of attribute field_names.



19
20
21
# File 'lib/active_hash/base.rb', line 19

def field_names
  @field_names
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



281
282
283
# File 'lib/active_hash/base.rb', line 281

def attributes
  @attributes
end

Class Method Details

.all(options = {}) ⇒ Object



70
71
72
73
74
75
76
77
78
# File 'lib/active_hash/base.rb', line 70

def all(options={})
  if options.has_key?(:conditions)
    (@records || []).select do |record|
      options[:conditions].all? {|col, match| record[col] == match}
    end
  else
    @records || []
  end
end

.auto_assign_fields(array_of_hashes) ⇒ Object



239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/active_hash/base.rb', line 239

def auto_assign_fields(array_of_hashes)
  (array_of_hashes || []).inject([]) do |array, row|
    row.symbolize_keys!
    row.keys.each do |key|
      unless key.to_s == "id"
        array << key
      end
    end
    array
  end.uniq.each do |key|
    field key
  end
end

.base_classObject

Needed for ActiveRecord polymorphic associations



256
257
258
# File 'lib/active_hash/base.rb', line 256

def base_class
  ActiveHash::Base
end

.configuration_for_custom_finder(finder_name) ⇒ Object



163
164
165
166
167
168
169
170
171
# File 'lib/active_hash/base.rb', line 163

def configuration_for_custom_finder(finder_name)
  if finder_name.to_s.match(/^find_(all_)?by_(.*?)(!)?$/) && !($1 && $3)
    {
      :all?   => !!$1,
      :bang?  => !!$3,
      :fields => $2.split('_and_')
    }
  end
end

.countObject



80
81
82
# File 'lib/active_hash/base.rb', line 80

def count
  all.length
end

.create(attributes = {}) ⇒ Object Also known as: add



55
56
57
58
59
60
# File 'lib/active_hash/base.rb', line 55

def create(attributes = {})
  record = new(attributes)
  record.save
  mark_dirty
  record
end

.create!(attributes = {}) ⇒ Object



64
65
66
67
68
# File 'lib/active_hash/base.rb', line 64

def create!(attributes = {})
  record = new(attributes)
  record.save!
  record
end

.data=(array_of_hashes) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/active_hash/base.rb', line 27

def data=(array_of_hashes)
  mark_dirty
  @records = nil
  write_inheritable_attribute(:data, array_of_hashes)
  if array_of_hashes
    auto_assign_fields(array_of_hashes)
    array_of_hashes.each do |hash|
      insert new(hash)
    end
  end
end

.define_custom_find_all_method(field_name) ⇒ Object



222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/active_hash/base.rb', line 222

def define_custom_find_all_method(field_name)
  method_name = "find_all_by_#{field_name}"
  unless singleton_methods.include?(method_name)
    the_meta_class.instance_eval do
      unless singleton_methods.include?(method_name)
        define_method(method_name) do |*args|
          options = args.extract_options!
          identifier = args[0]
          all.select { |record| record.send(field_name) == identifier }
        end
      end
    end
  end
end

.define_custom_find_method(field_name) ⇒ Object



207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/active_hash/base.rb', line 207

def define_custom_find_method(field_name)
  method_name = "find_by_#{field_name}"
  unless singleton_methods.include?(method_name)
    the_meta_class.instance_eval do
      define_method(method_name) do |*args|
        options = args.extract_options!
        identifier = args[0]
        all.detect { |record| record.send(field_name) == identifier }
      end
    end
  end
end

.define_getter_method(field, default_value) ⇒ Object



175
176
177
178
179
180
181
# File 'lib/active_hash/base.rb', line 175

def define_getter_method(field, default_value)
  unless instance_methods.include?(field.to_s)
    define_method(field) do
      attributes[field].nil? ? default_value : attributes[field]
    end
  end
end

.define_interrogator_method(field) ⇒ Object



196
197
198
199
200
201
202
203
# File 'lib/active_hash/base.rb', line 196

def define_interrogator_method(field)
  method_name = "#{field}?"
  unless instance_methods.include?(method_name)
    define_method(method_name) do
      send(field).present?
    end
  end
end

.define_setter_method(field) ⇒ Object



185
186
187
188
189
190
191
192
# File 'lib/active_hash/base.rb', line 185

def define_setter_method(field)
  method_name = "#{field}="
  unless instance_methods.include?(method_name)
    define_method(method_name) do |new_val|
      attributes[field] = new_val
    end
  end
end

.delete_allObject



90
91
92
93
# File 'lib/active_hash/base.rb', line 90

def delete_all
  mark_dirty
  @records = []
end

.field(field_name, options = {}) ⇒ Object



123
124
125
126
127
128
129
130
131
132
# File 'lib/active_hash/base.rb', line 123

def field(field_name, options = {})
  @field_names ||= []
  @field_names << field_name

  define_getter_method(field_name, options[:default])
  define_setter_method(field_name)
  define_interrogator_method(field_name)
  define_custom_find_method(field_name)
  define_custom_find_all_method(field_name)
end

.fields(*args) ⇒ Object



116
117
118
119
120
121
# File 'lib/active_hash/base.rb', line 116

def fields(* args)
  options = args.extract_options!
  args.each do |field|
    field(field, options)
  end
end

.find(id, *args) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/active_hash/base.rb', line 95

def find(id, * args)
  case id
    when nil
      nil
    when :all
      all
    when Array
      all.select { |record| id.map(& :to_i).include?(record.id) }
    else
      find_by_id(id) || begin
        raise RecordNotFound.new("Couldn't find #{name} with ID=#{id}")
      end
  end
end

.find_by_id(id) ⇒ Object



110
111
112
# File 'lib/active_hash/base.rb', line 110

def find_by_id(id)
  all.detect { |record| record.id == id.to_i }
end

.insert(record) ⇒ Object



39
40
41
42
43
44
# File 'lib/active_hash/base.rb', line 39

def insert(record)
  @records ||= []
  record.attributes[:id] ||= next_id
  mark_dirty
  @records << record
end

.mark_cleanObject



273
274
275
# File 'lib/active_hash/base.rb', line 273

def mark_clean
  self.dirty = false
end

.mark_dirtyObject



267
268
269
# File 'lib/active_hash/base.rb', line 267

def mark_dirty
  self.dirty = true
end

.method_missing(method_name, *args) ⇒ Object



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/active_hash/base.rb', line 144

def method_missing(method_name, *args)
  return super unless respond_to? method_name

  config = configuration_for_custom_finder(method_name)
  attribute_pairs = config[:fields].zip(args)
  matches = all.select { |base| attribute_pairs.all? { |field, value| base.send(field).to_s == value.to_s } }

  if config[:all?]
    matches
  else
    result = matches.first
    if config[:bang?]
      result || raise(RecordNotFound, "Couldn\'t find #{name} with #{attribute_pairs.collect {|pair| "#{pair[0]} = #{pair[1]}"}.join(', ')}")
    else
      result
    end
  end
end

.next_idObject



46
47
48
49
50
51
52
53
# File 'lib/active_hash/base.rb', line 46

def next_id
  max_record = all.max { |a, b| a.id <=> b.id }
  if max_record.nil?
    1
  elsif max_record.id.is_a?(Numeric)
    max_record.id.succ
  end
end

.reloadObject



260
261
262
263
# File 'lib/active_hash/base.rb', line 260

def reload
  self.data = read_inheritable_attribute(:data)
  mark_clean
end

.respond_to?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


134
135
136
137
138
139
140
141
142
# File 'lib/active_hash/base.rb', line 134

def respond_to?(method_name, include_private=false)
  super ||
    begin
      config = configuration_for_custom_finder(method_name)
      config && config[:fields].all? do |field|
        field_names.include?(field.to_sym) || field.to_sym == :id
      end
    end
end

.the_meta_classObject



21
22
23
24
25
# File 'lib/active_hash/base.rb', line 21

def the_meta_class
  class << self
    self
  end
end

.transactionObject



84
85
86
87
88
# File 'lib/active_hash/base.rb', line 84

def transaction
  yield
rescue ActiveRecord::Rollback

end

Instance Method Details

#[](key) ⇒ Object



291
292
293
# File 'lib/active_hash/base.rb', line 291

def [](key)
  attributes[key]
end

#[]=(key, val) ⇒ Object



295
296
297
# File 'lib/active_hash/base.rb', line 295

def []=(key, val)
  attributes[key] = val
end

#cache_keyObject



335
336
337
338
339
340
341
342
343
344
# File 'lib/active_hash/base.rb', line 335

def cache_key
  case
  when new_record?
    "#{self.class.model_name.cache_key}/new"
  when timestamp = self[:updated_at]
    "#{self.class.model_name.cache_key}/#{id}-#{timestamp.to_s(:number)}"
  else
    "#{self.class.model_name.cache_key}/#{id}"
  end
end

#destroyed?Boolean

Returns:

  • (Boolean)


313
314
315
# File 'lib/active_hash/base.rb', line 313

def destroyed?
  false
end

#eql?(other) ⇒ Boolean Also known as: ==

Returns:

  • (Boolean)


325
326
327
# File 'lib/active_hash/base.rb', line 325

def eql?(other)
  other.instance_of?(self.class) and not id.nil? and (id == other.id)
end

#errorsObject



346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/active_hash/base.rb', line 346

def errors
  obj = Object.new

  def obj.[](key)
    []
  end

  def obj.full_messages()
    []
  end

  obj
end

#hashObject



331
332
333
# File 'lib/active_hash/base.rb', line 331

def hash
  id.hash
end

#idObject Also known as: quoted_id



299
300
301
# File 'lib/active_hash/base.rb', line 299

def id
  attributes[:id] ? attributes[:id] : nil
end

#id=(id) ⇒ Object



303
304
305
# File 'lib/active_hash/base.rb', line 303

def id=(id)
  attributes[:id] = id
end

#marked_for_destruction?Boolean

Returns:

  • (Boolean)


371
372
373
# File 'lib/active_hash/base.rb', line 371

def marked_for_destruction?
  false
end

#new_record?Boolean

Returns:

  • (Boolean)


309
310
311
# File 'lib/active_hash/base.rb', line 309

def new_record?
  !self.class.all.include?(self)
end

#persisted?Boolean

Returns:

  • (Boolean)


317
318
319
# File 'lib/active_hash/base.rb', line 317

def persisted?
  self.class.all.map(&:id).include?(id)
end

#readonly?Boolean

Returns:

  • (Boolean)


321
322
323
# File 'lib/active_hash/base.rb', line 321

def readonly?
  true
end

#save(*args) ⇒ Object Also known as: save!



360
361
362
363
# File 'lib/active_hash/base.rb', line 360

def save(*args)
  self.class.insert(self)
  true
end

#to_paramObject



13
14
15
# File 'lib/active_hash/base.rb', line 13

def to_param
  id.present? ? id.to_s : nil
end

#valid?Boolean

Returns:

  • (Boolean)


367
368
369
# File 'lib/active_hash/base.rb', line 367

def valid?
  true
end