Skip to content

Instantly share code, notes, and snippets.

@hxegon
Last active March 24, 2017 16:34
Show Gist options
  • Save hxegon/e4b5bd34344d99b7fe6c0b1bf6c60955 to your computer and use it in GitHub Desktop.
Save hxegon/e4b5bd34344d99b7fe6c0b1bf6c60955 to your computer and use it in GitHub Desktop.
possible object design for ascio's browser problem [WIP]
# Roughly based on my https://github.com/hxegon/aok_product/blob/e417b2bc6df9d772d09bb025e502c46a548d55e9/lib/extractor.rb
# This possibley has a bug in Browser, with @@actions being a class instance var. Might be fixable by changing @browsers to
# class inst var, and adding during #add_action instead of pushing it off too #initialize
class Implementations
# Keeps track of what browsers are available, and what their actions are.
# default is what get returned when nothing matches the action_list you give #for
def initialize(actions=[], default:nil)
# actions format: [(class_name, action_name)], good candidate for class extraction or just a struct
@default = default
actions.each { |(action_name, class_name| add_action(class_name, action_name) }
end
def add_action(class_name, action_name)
implementations[class_name] << action_name
end
# Use this to search for an appropriate browser
def find_for(action_list)
implementations.each do |(klass, actions)|
return klass if (action_list - actions).empty?
end
# this only runs if there's no implementation matching the action_list
@default
end
private
def implementations
# Set because your actions are unique method names on a given class
@implementations ||= Hash.new { |_, _| Set.new }
end
end
class Browser
@@browsers = Implementations.new
class << self
def def_action(name, &block)
define_method(name.to_sym, block)
@@browsers.add_action(class.name, name)
end
def def_synchr_action(name, &block)
# Maybe change initialize to have a mutex parameter, def_action with the block in a Mutex#synchronize?
raise NotImplementedError
end
def browsers
@@browsers
end
end
end
class NilBrowser < Browser
# probably a good idea?
# Add sane standard nil actions?
end
browsers = Implementations.new(default: NilBrowser) # you could also make a DefaultBrowser
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment