Lannister Lannister - 2 years ago 56
Ruby Question

How to run this expression in ruby on rails

I have two models

class Filters < ActiveRecord::Base

class Groups < ActiveRecord::Base

Filter model is responsible for fetching user data from db e.g

SELECT users.* FROM users INNER JOIN notes ON notes.user_id = WHERE notes.category = 'Emotions'

SELECT users.* FROM users INNER JOIN subscriptions ON subscriptions.user_id = WHERE (Date(end_date) = CURDATE())

SELECT users.* FROM users WHERE (auth_token_created_at > DATE_SUB(NOW(), INTERVAL 2 hour))

Group model makes a group with multiple filters with AND and OR conditions e.g

group_id_1 =
"filter_id_1 AND filter_id_2 OR filter_id_3"

Now using group I am trying to fetch users by converting expression to methods according to AND OR conditions.

users = Filter.find(1).get_users & Filter.find(2).get_users | Filter.find(3).get_users

How can i convert this experssion from this
"filter_id_1 AND filter_id_2 OR filter_id_3"

to this

users = Filter.find(1).get_users & Filter.find(2).get_users | Filter.find(3).get_users

Answer Source

If you can, you might want to convert your group format to something more structured, like [1, '&', 2, '|', 3], which will make it easier to apply. If not, we can get there pretty quickly with some simple substitutions:

parts = 'filter_id_1 AND filter_id_2 OR filter_id_3'
  .gsub('filter_id_', '')
  .gsub('AND', '&')
  .gsub('OR', '|')
#=> ["1", "&", "2", "|", "3"]

Then you can construct your list of users by walking through the symbols:

parts = ["1", "&", "2", "|", "3"]
users = Filter.find(parts.shift).get_users
while parts.any?
  op = parts.shift
  next_users = Filter.find(parts.shift).get_users
  users = users.send(op, next_users)

As long as there's something left in parts (and assuming the group was well formed), you know there's an operation followed by another filter ID. Grabbing each of those, you can send the op to your existing users to apply the next set of users in the right way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download