Skip to content

Instantly share code, notes, and snippets.

@darrencauthon
Last active August 29, 2015 13:59
Show Gist options
  • Select an option

  • Save darrencauthon/10891039 to your computer and use it in GitHub Desktop.

Select an option

Save darrencauthon/10891039 to your computer and use it in GitHub Desktop.
Refactoring, a class for Hello World Open
class Message
def initialize value = nil
@data = {}
if value.is_a? Hash
value.each do |k, v|
@data[k.to_s.underscore] = v
end
else
self.type = value if value
end
end
def to_hash
data = {}
@data.each do |k, v|
data[k.camelize] = v
end
data.delete('type')
{ 'msgType' => type, 'data' => data }
end
def method_missing(meth, *args, &blk)
if meth.to_s[-1] == '='
@data[meth.to_s.gsub('=', '')] = args[0]
else
@data[meth.to_s]
end
end
end
class Message
def initialize value = nil
set_the_current_data_based_on_value value
end
def to_hash
{
'msgType' => type.to_s.camelize,
'data' => current_data_in_hello_world_open_format
}
end
def method_missing(method, *args, &blk)
if this_method_is_a_setter method
set_this_value method, args[0]
else
get_this_value method
end
end
private
def set_this_value name, value
key = name.to_s.gsub('=', '')
@data[key] = convert_value_to_object value
end
def get_this_value name
@data[name.to_s]
end
def this_method_is_a_setter method
method.to_s[-1] == '='
end
def convert_hash_values_to_objects hash
hash.reduce({}) do |data, item|
data.merge item[0].to_s.underscore => convert_value_to_object(item[1])
end
end
def convert_value_to_object value
if value.is_a? Array
value.map { |x| Message.new x }
elsif value.is_a? Hash
Message.new value
else
value
end
end
def set_the_current_data_based_on_value value
@data = {}
if value.is_a? Hash
@data = convert_hash_values_to_objects value
else
self.type = value if value
end
end
def current_data_in_hello_world_open_format
data = @data.reduce({}) { |h, i| h.merge i[0].camelize => i[1] }
data.delete('type')
data
end
end
@baweaver
Copy link
Copy Markdown

In hash reduce, you can do this to save a few lines:

@data.reduce({}) { |h, i| h.merge i[0].camelize => i[1] }

That can apply throughout.

@darrencauthon
Copy link
Copy Markdown
Author

thank you @baweaver! Change made.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment