Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ippeiukai/38cdc7b3c38fd578bc08 to your computer and use it in GitHub Desktop.
Save ippeiukai/38cdc7b3c38fd578bc08 to your computer and use it in GitHub Desktop.
# monkey patch for https://github.com/willbryant/columns_on_demand/issues/2
require 'active_record'
require 'columns_on_demand'
module ColumnsOnDemand
module BaseMethods
# COPIED
def columns_on_demand(*columns_to_load_on_demand)
class_attribute :columns_to_load_on_demand, :instance_writer => false
self.columns_to_load_on_demand = columns_to_load_on_demand.empty? ? blob_and_text_columns : columns_to_load_on_demand.collect(&:to_s)
extend ClassMethods
include InstanceMethods
class <<self
unless ActiveRecord::VERSION::MAJOR > 3 ||
(ActiveRecord.const_defined?(:AttributeMethods) &&
ActiveRecord::AttributeMethods::const_defined?(:Serialization) &&
ActiveRecord::AttributeMethods::Serialization::const_defined?(:Attribute))
alias_method_chain :define_read_method_for_serialized_attribute, :columns_on_demand
end
alias_method_chain :reset_column_information, :columns_on_demand
end
alias_method_chain :attributes, :columns_on_demand
alias_method_chain :attribute_names, :columns_on_demand
alias_method_chain :read_attribute, :columns_on_demand
alias_method_chain :read_attribute_before_type_cast, :columns_on_demand
alias_method_chain :missing_attribute, :columns_on_demand
alias_method_chain :reload, :columns_on_demand
# CHANGED = FROM HERE
alias_method_chain :attribute_changed_in_place?, :columns_on_demand if ActiveRecord::AttributeMethods::Dirty.instance_methods.include?(:changed_attributes)
alias_method_chain :_read_attribute, :columns_on_demand
# CHANGED = TO HERE
end
end
end
module ColumnsOnDemand
module InstanceMethods
def attribute_changed_in_place_with_columns_on_demand?(attr_name)
column_loaded?(attr_name) && attribute_changed_in_place_without_columns_on_demand?(attr_name)
end
def _read_attribute_with_columns_on_demand(attr_name, &block)
ensure_loaded(attr_name)
_read_attribute_without_columns_on_demand(attr_name, &block)
end
end
end
class ActiveRecord::Relation
# override build_select already chained to build_select_with_columns_on_demand
private \
def build_select(arel)
if select_values.any?
arel.project(*arel_columns(select_values.uniq))
else
if klass < ColumnsOnDemand::InstanceMethods
selects = [default_select(true)]
expanded_select = selects.map do |field|
if (Symbol === field || String === field) && columns_hash.key?(field.to_s)
arel_table[field]
else
field
end
end
arel.project(*expanded_select)
else
arel.project(@klass.arel_table[Arel.star])
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment