Created
October 27, 2017 19:19
-
-
Save kddnewton/e8bcedcf8a3879a38f73fa47f8c76750 to your computer and use it in GitHub Desktop.
Better selects for ActiveRecord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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