I wrote this method which I think is not effective as it doesn't respond to the missing method when I use the PORO Class.
BalanceService
class BalanceService
INITIAL_MULTIPLIER = 1
HUMUS_EFFECT = 1.3
instance_methods.each do |m|
undef_method m unless m.to_s =~ /^__|method_missing|respond_to?/
end
def initialize(field_data)
@field_data = field_data
end
def method_missing(name, *args)
super unless respond_to?(name) # If I remove this line it works.
@field_data.map do |field|
previous_value = nil
multiplier = INITIAL_MULTIPLIER
field[:humus_balance] = field[:crops].inject(0) do |balance, crop|
(crop[:crop][:value] == previous_value) ? multiplier = multiplier * HUMUS_EFFECT : previous_value = crop[:crop][:value]
balance + (crop[:crop][:humus_delta] * field[:area] * multiplier)
end
field
end
end
def respond_to?(method)
@field_data.respond_to?("get_#{method}_info") || super
end
end
When I call it in the fetch_field
method below I get undefined method "field_data" for #<BalanceService:0x00007fda9c190e28>
. However, if I remove super unless respond_to?(name)
from BalanceService class above, it works. I indeed want BalanceService to respond to missing methods.
FieldService
class FieldsService
include Singleton
def fetch_fields
value = BalanceService.new(field_data)
value.field_data
end
private
def field_data
# some JSON
end
end
super unless respond_to?(name)
removed work as intended? \$\endgroup\$