Last active
August 29, 2015 14:05
-
-
Save singpolyma/d2de0ba53cf5e6ce9935 to your computer and use it in GitHub Desktop.
JSON Template
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
| @model = OpenStruct.new(name: 'steve', age: 12, contacts: [{name: 'steve', sekret: 6}], other: 'stuff', moar: 'things') | |
| json @model, | |
| :name, | |
| :age, | |
| oldness: :age, | |
| friends: [nested(:name), from: :contacts], | |
| contacts: nested('contact_partial', :model) | |
| other: ->(c) { c + 'hai' }, | |
| stuff: [->(c) { c + 'you' }, from: :moar] |
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
| json [@model], | |
| this: :name |
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
| {people: (json [@model], | |
| this: :name | |
| )} |
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
| def get_or_map(k, v, object) | |
| if v.respond_to?(:call) | |
| v.call(object.public_send(k)) | |
| elsif v.is_a?(Array) | |
| v.last.call(object.public_send(v.first)) | |
| else | |
| object.public_send(v) | |
| end | |
| end | |
| def nested(*args) | |
| lambda do |*largs| | |
| if largs.first.is_a?(String) | |
| # Get partial and render | |
| else | |
| json(largs.first, *args) | |
| end | |
| end | |
| end | |
| def json(*args) | |
| object = args.shift | |
| object = OpenStruct.new(object) if object.is_a?(Hash) | |
| if object.respond_to?(:map) | |
| object.map { |x| json(x, *args) } | |
| else | |
| extra = args.last.is_a?(Hash) ? args.pop : {} | |
| h = args.each_with_object({}) do |k, h| | |
| h[k] = get_or_map(k, k, object) | |
| end | |
| extra.each_with_object(h) do |(k, v), h| | |
| h[k] = get_or_map(k, v, object) | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment