Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/spyro/active_record_add_on.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default(field, value, opts = {}) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/spyro/active_record_add_on.rb', line 19

def self.default field, value, opts = {}
  opts = {:forced => false, :method => :blank?, :action => :before_validation}.merge opts
  fct = "#{field}_#{opts[:action]}".to_sym

  self.send(opts[:action], fct)

  define_method fct do
    return true if opts[:if]      and not opts[:if].call(*(opts[:if].arity.zero? ? [] : [self]))
    return true if opts[:unless]  and     opts[:unless].call(*(opts[:unless].arity.zero? ? [] : [self]))

    if opts[:forced] == true or self.send(field.to_sym).send(opts[:method])
      final_value = value.respond_to?(:call) ? value.call(*(value.arity.zero? ? [] : [self])) : value
      self.send("#{field.to_sym}=", final_value)
    end

    true
  end
end

.primary_keyObject



3
4
5
# File 'lib/spyro/active_record_add_on.rb', line 3

def self.primary_key
  "id"
end

Instance Method Details

#primary_keyObject



7
8
9
# File 'lib/spyro/active_record_add_on.rb', line 7

def primary_key
  "id"
end

#to_desc(*args) ⇒ Object



11
12
13
# File 'lib/spyro/active_record_add_on.rb', line 11

def to_desc *args
  self.send self.to_desc_sym *args
end

#to_desc_sym(*args) ⇒ Object



15
16
17
# File 'lib/spyro/active_record_add_on.rb', line 15

def to_desc_sym *args
  self.respond_to?(:name) ? :name : :id
end