Module: Ramaze::StateAccessor

Included in:
Trinity
Defined in:
lib/ramaze/snippets/ramaze/state.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.each(*names) ⇒ Object

Iterate over the names and yield accordingly. names are either objects responding to #to_sym or hashes.

It’s only used within this module for abstractin-purposes. Usage below.



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/ramaze/snippets/ramaze/state.rb', line 40

def self.each(*names)
  names.each do |name|
    if name.respond_to?(:to_hash)
      name.to_hash.each do |key, meth|
        key, meth = key.to_sym, meth.to_sym
        yield key, meth
      end
    else
      key = meth = name.to_sym
      yield key, meth
    end
  end
end

Instance Method Details

#state_accessor(*names, &initializer) ⇒ Object

state_writer and state_reader, initializer is a block that may be given and its result will be the new value in case the reader was never called before or the value wasn’t set before.



57
58
59
60
# File 'lib/ramaze/snippets/ramaze/state.rb', line 57

def state_accessor(*names, &initializer)
  state_writer(*names)
  state_reader(*names, &initializer)
end

#state_reader(*names, &initializer) ⇒ Object

Reader accessor for STATE



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/ramaze/snippets/ramaze/state.rb', line 70

def state_reader(*names, &initializer)
  StateAccessor.each(*names) do |key, meth|
    if initializer
      define_method(meth) do
        unless STATE.key?(key)
          STATE[key] = instance_eval(&initializer)
        else
          STATE[key]
        end
      end
    else
      define_method(meth){ STATE[key] }
    end
  end
end

#state_writer(*names) ⇒ Object

Simple writer accessor to STATE=



63
64
65
66
67
# File 'lib/ramaze/snippets/ramaze/state.rb', line 63

def state_writer(*names)
  StateAccessor.each(*names) do |key, meth|
    define_method("#{meth}="){|obj| STATE[key] = obj }
  end
end