module TrivialTokens::Tokenize::ClassMethods

Public Instance Methods

tokenize(relation) click to toggle source
# File lib/trivial_tokens/tokenize.rb, line 12
def tokenize(relation)

  reflection = self.reflect_on_association(relation)

  if !reflection
    raise TrivialTokens::Tokenize::UntokenizableAssociationError, "Association #{relation} not found!"
  elsif !(reflection.macro == :has_many || reflection.macro == :has_and_belongs_to_many)
    raise TrivialTokens::Tokenize::UntokenizableAssociationError,
          "Expected association #{relation} to be of has_many or has_and_belongs_to_many, was #{reflection.macro}"
  end

  #relation is a symbol representing the relation to be tokenized
  self.send( :define_method, "tokenized_#{relation.to_s}" ) do
    self.send("#{relation.to_s.singularize}_ids").join(',')
  end

  self.send( :define_method, "tokenized_#{relation.to_s}=" ) do |tokens|
    self.send("#{relation.to_s.singularize}_ids=", tokens.split(','))
  end
end