Class: ViewModel
- Inherits:
-
Object
- Object
- ViewModel
- Defined in:
- app/models/view_model.rb
Direct Known Subclasses
Formstrap::AssociationView, Formstrap::CheckboxView, Formstrap::ColorView, Formstrap::DateRangeView, Formstrap::DateView, Formstrap::DatetimeRangeView, Formstrap::DatetimeView, Formstrap::EmailView, Formstrap::FileView, Formstrap::FlatpickrRangeView, Formstrap::FlatpickrView, Formstrap::HiddenView, Formstrap::HintView, Formstrap::InputGroupView, Formstrap::LabelView, Formstrap::MediaItemView, Formstrap::MediaView, Formstrap::NumberView, Formstrap::PasswordView, Formstrap::RedactorView, Formstrap::SearchView, Formstrap::SelectView, Formstrap::SwitchView, Formstrap::TextView, Formstrap::TextareaView, Formstrap::ThumbnailView, Formstrap::UrlView, Formstrap::WrapperView, Formstrap::WysiwygView
Instance Method Summary collapse
- #attributes ⇒ Object
-
#initialize(hash = {}) ⇒ ViewModel
constructor
View Model.
- #to_hash ⇒ Object (also: #to_h)
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
#attributes ⇒ Object
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_hash ⇒ Object 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 |