Skip to content

Instantly share code, notes, and snippets.

@uberllama
Created April 29, 2015 01:22
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save uberllama/9e69529b0d835902f33d to your computer and use it in GitHub Desktop.
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
Copy link
Author

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