Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marshallshen/9f093c3b3b0a24dc3df69adcbab26c6a to your computer and use it in GitHub Desktop.
Save marshallshen/9f093c3b3b0a24dc3df69adcbab26c6a to your computer and use it in GitHub Desktop.
Rules Engine
module RulesEngine
def self.call(pipeline, data)
pipeline.each_with_object(data) do |pipe, memo|
result = pipe.call(memo)
memo.merge!(result)
end
end
class Extract
def self.call(data)
result = {}
result[:rules] = find_rules(data)
result[:videos] = find_videos(data.merge(result))
result
end
end
class Select
def self.call(data)
result = {}
result[:selected_videos] = find_selected_videos(data)
result
end
end
class Sort
def self.call(data)
result = {}
result[:playlist] = find_playlist(data)
result
end
end
class Validate
def self.call(data)
result = {}
result[:score] = find_score(data)
result
end
end
end
class Selector
attr_accessor :select_rules, :videos, :selected_videos
def initialize(options={})
@select_rules = options[:select_rules]
@videos = options[:videos]
@selected_videos = []
end
def run!
@selected_videos = @videos.select{|v| v.compatible?(@select_rules) }
end
end
class Sorter
attr_accessor :sort_rules, :selector, :playlist
def initialize(options={})
@sort_rules = options[:sort_rules]
@selector = options[:selector]
@playlist = []
end
def run!
@playlist = sort_by_rules(@sort_rules, @selector.selected_videos)
end
end
class Validator
attr_accessor :sorter, :rules
def initialize(options={})
@sorter = options[:sorter]
@rules = @sorter.sort_rules + @sorter.selector.select_rules
end
def run!
is_valid?(@sorter.playlist, @rules)
end
end
class Youtube
def self.pipeline
[
RulesEngine::Extract,
RulesEngine::Select,
RulesEngine::Sort,
RulesEngine::Validate,
]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment