Module: EntityStatus::ClassMethods

Defined in:
lib/entity_status.rb

Instance Method Summary collapse

Instance Method Details

#create_finder_methods(column_name, name) ⇒ Object



62
63
64
65
66
67
68
69
# File 'lib/entity_status.rb', line 62

def create_finder_methods(column_name,name)
  klass = self.to_s
  metaclass.instance_eval do
    define_method(name){
      where(column_name.to_sym => name)
    }
  end
end

#create_statuses_method(name, statuses) ⇒ Object



51
52
53
54
55
56
57
58
59
60
# File 'lib/entity_status.rb', line 51

def create_statuses_method(name,statuses)
  klass = self.to_s
  metaclass.instance_eval do
    # attr_accessor :statuses        
    # @@statuses = statuses
    define_method(name){
      return statuses
    }
  end
end

#entity_status(column_name = "status", status_array = [], options = { destroyed_status: nil}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/entity_status.rb', line 12

def entity_status(column_name="status",status_array = [], options = { destroyed_status: nil})
  status_array = (status_array.count > 0) ? status_array : %W(pending open closed)

  if options[:destroyed_status]
    status_array << options[:destroyed_status]
    self.set_default_scope(column_name, options[:destroyed_status])
    
    define_method 'destroyed_status' do
      options[:destroyed_status]
    end
  end
  
  self.create_statuses_method(column_name.to_s.pluralize,status_array)
  status_array.each do |st|
    self.create_finder_methods(column_name,st)
    # add dynamic state setters based on the status string
    # example: Post.first.pending #=> 'pending'
    define_method st do
      self.send("#{column_name}=".to_sym,st.to_s)
      self
    end
    
    # Add boolean state checks based on the status string
    # example: Post.first.pending? #=> true
    define_method "#{st}?" do
      (self.send(column_name) == st) ? true :false
    end
  end
  
end

#set_default_scope(column_name, destroyed_status) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/entity_status.rb', line 43

def set_default_scope(column_name,destroyed_status)
  self.default_scope {where.not(column_name.to_sym => destroyed_status)}
  # klass = self.to_s
  # metaclass.instance_eval do
  #   default_scope where.not(column_name.to_sym => destroyed_status)
  # end
end