Sha256: 4a21014073f34abd484410e4e745a1d44801390bc77ed14f6aadcf695ff51832

Contents?: true

Size: 1.4 KB

Versions: 4

Compression:

Stored size: 1.4 KB

Contents

module Marty
  module LazyColumnLoader
    extend ActiveSupport::Concern

    module ClassMethods
      def lazy_load(*columns)
        return unless table_exists?
        columns = columns.collect(&:to_s)
        exclude_columns_from_default_scope columns
        define_lazy_accessors_for columns
      end

    private
      def exclude_columns_from_default_scope(columns)
        default_scope select((
                              column_names - columns).map {
                               |column_name|
                               "#{table_name}.#{column_name}"
                             })
      end

      def define_lazy_accessors_for(columns)
        columns.each { |column| define_lazy_accessor_for column }
      end

      def define_lazy_accessor_for(column)
        define_method column do
          unless has_attribute?(column)
            changes_before_reload = self.changes.clone
            self.reload
            changes_before_reload.each{|attribute_name, values|
              self.send("#{attribute_name}=", values[1])}
          end
          read_attribute column
        end
      end
    end
  end
end

if ActiveRecord::Base.respond_to?(:lazy_load)
  $stderr.puts "ERROR: Method `.lazy_load` already defined in " +
    "`ActiveRecord::Base`. This is incompatible with LazyColumnLoader " +
    "and the module will be disabled."
else
  ActiveRecord::Base.send :include, Marty::LazyColumnLoader
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
marty-0.5.15 lib/marty/lazy_column_loader.rb~
marty-0.5.14 lib/marty/lazy_column_loader.rb~
marty-0.5.13 lib/marty/lazy_column_loader.rb~
marty-0.5.12 lib/marty/lazy_column_loader.rb~