Skip to content

lucashungaro/scoring_rules

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

scoring_rules

A small library that provides a simple DSL for creating scoring rules (for rankings, rating and similar uses).

Does scoring_rules helps your daily work with Rails? So, please recommend me on Working With Rails. Thanks for your kindness! :)

Why?

This kind of feature could be implemented without a DSL, but this really helps to build a transparent representation of business rules that is self-contained and easier to modify. Also, even if not a primary goal, this way of representation is easier for non-tech people to understand.

How?

First, install the gem:

$ [sudo] gem install scoring_rules

Then, add it as a dependency in your code using your favorite way (a simple require or mechanisms like the Bundler gem).

The gem will provide you a module to mixin into your classes.

class User
  include ScoringRules

  scoring_rules do |rule|
    rule.add_points    10, :if => lambda {self.age >= 18} # adds 10
    rule.remove_points  5, :if => :can_remove? # removes 5
    rule.add_points     5, :unless => lambda {self.is_new_user?} # does nothing
    rule.add_points     1, :each => :followers # adds 300
  end

  def followers
    OpenStruct.new(:count => 300)
  end

  def can_remove?
    true
  end

  def age
    20
  end

  def is_new_user?
    true
  end
end

Each rule requires one condition, expressed through :if, :unless or :each. For now you can’t supply more than one condition per rule (it was a goal, but proved unnecessary).

For :if and :unless you simple need something that returns true or false (or anything that Ruby will understand as true or false). It can be a proc or method.

For :each, you need to return a object that responds to count (that’s why I used the OpenStruct in the sample code above).

And to calculate the score, it’s really simple:

> user = User.get_me_some_user_from_somewhere
> user.calculate_score
=> 305

Note on Patches/Pull Requests

  • Fork the project.
  • Make your feature addition or bug fix.
  • Add tests for it. This is important so I don’t break it in a
    future version unintentionally.
  • Commit, do not mess with rakefile, version, or history.
    (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
  • Send me a pull request. Bonus points for topic branches.

Contributors

Be a contributor! :)

License

scoring_rules is released under the MIT license. See MIT LICENSE.

About

A small library that provides a simple DSL for creating scoring rules (for rankings, rating and similar uses)

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages