Jan
Jan

Reputation: 16214

Merge methods to one hash, through method chaining

I have a class which is generating queries for a db:

They should concatenated, so I do not repeat my code for a query (DRY).

I thought I could do something like this:

ruby

class Blah < ActiveRecord::Base
  def no_scope
    {scope: false}
  end

  def for_user(user_id)
    {user_id: user_id}
  end
end

Now my query

    Blah.no_scope.for_user(1)

RESULT SHOULD BE A HASH:

    {user_id: 1, scope: false}

Upvotes: 1

Views: 89

Answers (3)

peter
peter

Reputation: 42207

To give the result as a real Hash instead of a Activerecord relation, you do it like this

class Blah < ActiveRecord::Base
  scope :no_scope, ->{where(scope: false)}
  scope :for_user, ->(id){where(user_id: id)} # no space in ->(id)
end

# give results as an array of hashes
Blah.no_scope.for_user(1).map { |e| {scope: e.scope, user_id: e.user_id} }

gives

[{"scope"=>false, "user_id"=>1}]

Upvotes: 0

Piotr Kruczek
Piotr Kruczek

Reputation: 2390

Did you try to achieve this?

class Blah < ActiveRecord::Base
  scope :no_scope, -> { where(scope: false) }
  scope :for_user, -> (id) { where(user_id: id) }
end

Blah.no_scope.for_user(1) #  where(scope: false, user_id: 1)

Upvotes: 2

Nermin
Nermin

Reputation: 6100

You just need to create scopes.

class Blah < ActiveRecord::Base
  scope :no_scope, -> {all}
  scope :for_user, -> (user_id) {where(user_id: user_id)} 

end


Blah.no_scope.for_user(1) #  where(user_id: 1)

See also scopes

Upvotes: 0

Related Questions