Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
relation inheritance
class PostQuery
attr_accessor :relation
ALLOWED_SORT_ATTRS = ["title", "updated_at"]
# @example PostQuery.new.relation.recent.sorted("title", "DESC")
# @example PostQuery.new(user.posts).relation.recent.sorted("title", "DESC")
#
def initialize(relation = nil)
relation ||= Post.all
self.relation = relation.extending(Scopes)
end
module Scopes
include BaseQuery::Scopes
def recent
where("updated_at > ?", 1.day.ago)
end
end
end
class BaseQuery
module Scopes
def sorted(sort_param, sort_direction)
# This won't work
# How to access this const in included module
if ALLOWED_SORT_ATTRS.include(sort_param)
order("#{sort_param} #{sort_direction}")
else
order("id DESC")
end
end
end
end
@uberllama

This comment has been minimized.

Copy link
Owner Author

@uberllama uberllama commented Apr 30, 2015

This doesn't work either and actually removes the const from the sub class:

class PostQuery < BaseQuery

  attr_accessor :relation

  ALLOWED_SORT_ATTRS = ["title", "updated_at"]

  # @example PostQuery.new.relation.recent.sorted("title", "DESC")
  # @example PostQuery.new(user.posts).relation.recent.sorted("title", "DESC")
  #
  def initialize(relation = nil)
    super(relation ||= Post.all)
    @relation = @relation.extending(Scopes)
  end

  module Scopes
    def recent
      where("updated_at > ?", 1.day.ago)
    end
  end

end

class BaseQuery

  def initialize(relation)
    @relation = relation.extending(Scopes)
  end

  def self.inherited(sub_klass)
   # uninitialized constant PostQuery:: ALLOWED_SORT_ATTRS
    puts sub_klass.const_get(: ALLOWED_SORT_ATTRS)
  end

  module Scopes
    def sorted(sort_param, sort_direction)
      # This won't work
      # How to access this const in included module
      if ALLOWED_SORT_ATTRS.include(sort_param)
        order("#{sort_param} #{sort_direction}")
      else
        order("id DESC")
      end
    end
  end

end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.