Sha256: 3a4fd6263dcf7699646e68e027931cc78503199e0f63a245b87deaaff8c1432e

Contents?: true

Size: 957 Bytes

Versions: 5

Compression:

Stored size: 957 Bytes

Contents

module ActiveUrl
  module BelongsTo
    def belongs_to(object_name)
      begin
        object_name.to_s.classify.constantize
      
        attribute_name = "#{object_name}_id"
        attribute attribute_name
    
        define_method object_name do
          begin
            object_name.to_s.classify.constantize.find(send(attribute_name))
          rescue ActiveRecord::RecordNotFound
            nil
          end
        end
    
        define_method "#{object_name}=" do |object|
          if object.nil?
            self.send "#{object_name}_id=", nil
          elsif object.is_a?(object_name.to_s.classify.constantize)
            self.send "#{object_name}_id=", object.id
          else
            raise TypeError.new("object is not of type #{object_name.to_s.classify}")
          end
        end
      rescue NameError
        raise ArgumentError.new("#{object_name.to_s.classify} is not an ActiveRecord class.")
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 2 rubygems

Version Path
mholling-active_url-0.1.1 lib/active_url/belongs_to.rb
mholling-active_url-0.1.2 lib/active_url/belongs_to.rb
mholling-active_url-0.1.3 lib/active_url/belongs_to.rb
mholling-active_url-0.1.4 lib/active_url/belongs_to.rb
active_url-0.1.4 lib/active_url/belongs_to.rb