3

In a question I've previously answered, I used an association extension to override a HABTM collection's append (<<) method (Also, a similar question):

has_and_belongs_to_many(:countries) do
  def <<(country)
    if [*country].all? {|c| c.is_a?(String) }
      countries = Country.where(:code => country)
      concat(*countries)
    else
      concat(country)
    end
  end
end

This is probably not encouraged, but my question is, how can one override, if even possible, the assignment operator, so I can do countries = ['IL', 'US'] with the same results?

Community
  • 1
  • 1
GeReV
  • 3,195
  • 7
  • 32
  • 44
  • Could you explain a little more? I don't really know what you want to do – basgys May 31 '13 at 14:00
  • The idea is to have a collection relationship to which I could assign both an array of objects (`[obj1, obj2, ...]`) and an array of object keys (`[key1, key2, ...]`). – GeReV Jun 01 '13 at 01:21

1 Answers1

0

I think that it could be something like:

def =(countries)
  values = countries.kind_of?(Hash) ? countries.values : countries
  values.each do |country|
    self << country
  end
end

I'm not sure if you can use the operator << that way.

basgys
  • 4,320
  • 28
  • 39