Last active
December 15, 2015 10:38
-
-
Save kornypoet/5246671 to your computer and use it in GitHub Desktop.
Gorillib::Model #field usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'gorillib/model' | |
| # In this first example, we have a User that will have a first and last name, and a synthetic secret_id. | |
| # The secret_id could be provided, but if it is not, we want to supply a default based on the names. | |
| # We need access to the other fields being received, so we used a delayed default: | |
| class User | |
| include Gorillib::Model | |
| field :first_name, String | |
| field :last_name, String | |
| field :secret_id, String, default: ->(){ Digest::MD5.hexdigest(first_name + last_name) } | |
| end | |
| # The above allows this to work: | |
| user = User.receive(first_name: 'Bob', last_name: 'Barker', secret_id: '45655ef5b6496fca9df96fbae6398e0a') | |
| user.secret_id | |
| #=> "45655ef5b6496fca9df96fbae6398e0a" | |
| # It also supplies a default, only created when #secret_id is called: | |
| user = User.receive(first_name: 'Bob', last_name: 'Barker') | |
| user.secret_id | |
| #=> "45655ef5b6496fca9df96fbae6398e0a" | |
| # If you would like to receive a field in a particular way, perhaps to do some light pre-processing, | |
| # you can override the receive_<field_name> method | |
| class User | |
| include Gorillib::Model | |
| field :first_name, String | |
| field :last_name, String | |
| def receive_last_name param | |
| normalized = param.downcase.slice(0..7) | |
| write_attribute(normalized) | |
| end | |
| end | |
| # In the above case, every last_name receieved will be nomalized. The #write_attribute method is the hook | |
| # Gorillib provides for setting the field in question. | |
| u = User.receive(first_name: 'Arnold', last_name: 'Schwarzenegger') | |
| u.last_name | |
| #=> "schwarze" | |
| # Gotchas: | |
| # The #receive method expects a Hash to be provided. Don't try to receive anything else. | |
| # | |
| # If you call #receive with a hash that contains keys that are not defined as fields, | |
| # they will be accessible via the @_extra_attributes instance variable. | |
| # No guarantees or sanitization happens to the extra attributes; they are stored as-is. | |
| user = User.receive(foo: 'bar', baz: 'qux') | |
| user.instance_variable_get('@_extra_attributes') | |
| #=> { :foo => "bar", :baz => "qux" } | |
| # | |
| # When #receive is called with a key pointing to nil, then the field is set to nil. | |
| # Note: this will NOT assign default values. | |
| user = User.receive(secret_id: nil) | |
| user.secret_id | |
| #=> nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment