I am new to Ruby and not familiar with a lot of Array
features. I feel like this code can be written in a couple of fewer lines.
The idea is: I have a Definition
class and a Field
class. I abstracted them as Hashes to make my life easier although they should be classes.
Definition
contains anId
and aName
Field
contains anId
and aValue
I want a resulting Hash that contains a Name
key for each corresponding Value
. However, if the name is repeated, then I need to include the Id
in the Name
.
Here's the code for generating mock objects:
# name and id
def mock_definitions
d = []
d << {
:name => "custom def 1",
:id => 1
}
d << {
:name => "custom def 2",
:id => 2
}
d << {
:name => "custom def 2",
:id => 3
}
d
end
def mock_fields
f = []
f << {
:id => 1,
:value => "Value For Custom Definition 1"
}
f << {
:id => 2,
:value => "Value For Custom Definition 2"
}
f << {
:id => 3,
:value => "Value For Custom Definition 3"
}
f
end
def all_mocks
return mock_definitions, mock_fields
end
############# END OF MOCK ###############
and the main logic preceded by helper functions:
def build_counter_cache(definitions = [])
counter_cache = Hash.new
definitions.each do |d|
if counter_cache.has_key?(d[:name])
counter_cache[d[:name]] +=1
else
counter_cache[d[:name]] = 1
end
end
counter_cache
end
def build_fields_cache(fields = [])
fields_cache = Hash.new
fields.each do |f|
fields_cache[f[:id]] = f[:value]
end
fields_cache
end
def build_search_to_replace_mapping(fields = [], definitions = [])
counter_cache = build_counter_cache(definitions)
custom_fields_cache = build_fields_cache(fields)
mapping = Hash.new
definitions.each do |d|
search_text = ''
replace_text = ''
if counter_cache[d[:name]] == 1
search_text = "{{#{d[:name]}}}"
else
search_text = "{{#{d[:name]}_#{d[:id]}}}"
end
if custom_fields_cache.has_key?(d[:id])
replace_text = custom_fields_cache[d[:id]]
end
#puts "#{search_text} maps to #{replace_text}"
mapping[search_text] = replace_text
end
mapping
end
### main logic begins here ###
# mocks
definitions, fields = all_mocks
mapping = build_search_to_replace_mapping(fields, definitions)
mapping.each do |key, value|
puts "#{key} *** maps to *** #{value}"
end
Struct
andOpenStruct
? They create classes and/or objects from Hashes. \$\endgroup\$