Skip to content

Instantly share code, notes, and snippets.

@igorkasyanchuk
Last active December 14, 2015 09:29
Show Gist options
  • Save igorkasyanchuk/5065060 to your computer and use it in GitHub Desktop.
Save igorkasyanchuk/5065060 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'json'
module Base
def fields
@fields ||= params.is_a?(String) ? JSON.parse(params) : params
end
def [](field)
fields[field]
end
def []=(field, value)
@fields[field] = value
end
def keys
fields.keys
end
def to_json
fields.to_json
end
def method_missing(meth, *args, &block)
method_name = meth.to_s
if keys.include?(method_name)
self[method_name]
elsif keys.include?(method_name.gsub!('=', ''))
self[method_name] = args.first
else
super
end
end
end
Room = Struct.new :params do
include Base
end
Hotel = Struct.new :params do
include Base
def rooms
@rooms ||= self["rooms"].collect{|room| Room.new(room)}
end
end
hotel = Hotel.new("{\"name\":\"Nadiya\",\"location\":\"Ivano-Frankivsk\",\"rooms\":[{\"name\":\"Lux\"},{\"name\":\"Standard\"}]}")
puts hotel.name
puts hotel.rooms.first.name
hotel.name = "NEW NAME"
puts hotel.name
puts hotel.to_json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment