Skip to content

Instantly share code, notes, and snippets.

@kddnewton
Created October 27, 2017 19:19
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 kddnewton/e8bcedcf8a3879a38f73fa47f8c76750 to your computer and use it in GitHub Desktop.
Save kddnewton/e8bcedcf8a3879a38f73fa47f8c76750 to your computer and use it in GitHub Desktop.
Better selects for ActiveRecord
class << ActiveRecord::Base
prepend Module.new {
class SelectChain < BasicObject
INVALID_ARGUMENTS =
'.select.not arguments must be a list of one or more symbols'.freeze
def initialize(scope)
@scope = scope
end
def method_missing(method_name, *arguments, &block)
select.public_send(method_name, *arguments, &block)
end
def not(*columns)
if columns.empty? || (columns - scope_columns).any?
raise ArgumentError, ERROR
end
select(scope_columns - columns)
end
private
def select(columns = scope_columns)
@select ||= @scope.select(*columns)
end
def scope_columns
@scope.column_names.map(&:to_sym)
end
end
def select(chain = :chain, *)
!block_given? && chain == :chain ? SelectChain.new(all.spawn) : super
end
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment