Sha256: fc29901d6a1c6c76de875097bca53d58c6a563dbc0cc634db5412367b4cde552

Contents?: true

Size: 1.19 KB

Versions: 2

Compression:

Stored size: 1.19 KB

Contents

module LazyModelSupport
	extend ActiveSupport::Concern
	
	included do
		attr_accessor :raw_attribute, :enumerables, :custom_finders, :column, :model, :attribute, :belongs_to
	end
	
	def initialize(model, raw_attribute, enumerables = nil, custom_finders = {})
		self.model 			= model
		self.raw_attribute 	= raw_attribute
		self.enumerables 	= Array(enumerables)
		self.custom_finders = custom_finders
		calculate_atttribute_and_belongs_to
	end

	def to_method_name(any_string_or_symbol)
		any_string_or_symbol.to_s.underscore
	end

	private

	def calculate_atttribute_and_belongs_to
		if raw_attribute.is_a?(Hash)
			self.belongs_to = raw_attribute.keys.first
			self.attribute 	= raw_attribute[belongs_to]
		else
			self.attribute = raw_attribute
		end
	end

	def belongs_to_attribute
		belongs_to ? "#{belongs_to}.#{attribute}" : attribute
	end

	def define_join_finder_method
		if belongs_to
			model.class_eval <<-LZY
				class << self
					def #{joins_method_name}
						joins(:#{belongs_to})
					end
				end
			LZY
		end
	end

	def klass
		belongs_to ? "#{belongs_to.to_s.camelize}" : "self"
	end

	def joins_method_name
		"with_#{belongs_to}"
	end

	def joins
		belongs_to ? "#{joins_method_name}." : nil
	end


end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
lazy_model-0.1.0 lib/lazy_model/lazy_model_support.rb
lazy_model-0.0.13 lib/lazy_model/lazy_model_support.rb