andela-amagana
12/5/2017 - 8:15 AM

Using define_method & method_missing

# Using define_method

%w(published unpublished draft).each do |possible_status|
  define_method("#{possible_status}") do
    possible_status
  end
end

# Using method_missing

class CarModel
 def method_missing(name, *args)
  name = name.to_s

  super unless name =~ /(_info|_price)=?$/

  name =~ /=$/ ? instance_variable_set("@#{name.chop}", args.first) : instance_variable_get("@#{name}")
 end
end

@car_model = CarModel.new

@car_model.stereo_info    = "CD/MP3 Player"
@car_model.stereo_price   = "£79.99"

@car_model.stereo_info  # => "CD/MP3 Player"
@car_model.stereo_price # => "£79.99"


# =~ is used to compare a string to a regex pattern

# We invoke super for methods that don't end in _info or _price. Invoking super
# call method_missing of the parent class which eventually raises NoMethodError