Class: ViewModel

Inherits:
Object
  • Object
show all
Defined in:
app/models/view_model.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ ViewModel

View Model

A View Model is a class that allows you to set an arbitrary hash of attributes and access all values by calling attribute methods.

Examples

model = ViewModel.new(a: 1, b: {b1: 1, b2: 2}, c: 3)

model.a   # => 1
model.b   # => {b1: 1, b2: 2}
model.c   # => 3

Reserved methods or attributes are left untouched. If you want to access an attribute that collides with a reserved method, you can do it via the to_hash method.

model = ViewModel.new(class: "test")

model.class             # => ViewModel
model.to_hash[:class]   # => "test"


25
26
27
28
29
# File 'app/models/view_model.rb', line 25

def initialize(hash = {})
  hash.each do |key, value|
    instance_variable_set("@#{key}", value)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object (private)



51
52
53
# File 'app/models/view_model.rb', line 51

def method_missing(m, *args, &block)
  instance_variable_get("@#{m}")
end

Instance Method Details

#attributesObject



31
32
33
# File 'app/models/view_model.rb', line 31

def attributes
  instance_variables.map { |instance_variable| instance_variable.to_s.delete("@").to_sym }
end

#to_hashObject Also known as: to_h



35
36
37
# File 'app/models/view_model.rb', line 35

def to_hash
  attributes.map { |attribute| {attribute => value_for(attribute)} }.inject(:merge) || {}
end