Created
          October 23, 2013 06:24 
        
      - 
      
- 
        Save elskwid/7113427 to your computer and use it in GitHub Desktop. 
    Another enum-ish example
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | class SomeTypes | |
| @all = [ | |
| ["TypeA", "Type A"], | |
| ["Type B", "Type B"], | |
| ] | |
| Type = Struct.new(:type, :name, :slug, :sym) do | |
| alias_method :to_ary, :to_a | |
| # allows Type to be used for ifnone option in .find | |
| def self.call | |
| new | |
| end | |
| end | |
| Type.members.each do |member| | |
| # define named helpers to return all i.e. .types, .names, .slugs | |
| define_singleton_method member.to_s.pluralize do | |
| all.map(&member) | |
| end | |
| # named finder i.e. .by_type, .by_name, .by_slug | |
| define_singleton_method "by_#{member}" do |cond| | |
| find(member => cond) | |
| end | |
| end | |
| ALL = Array.new.tap do |all| | |
| @all.each do |ary| | |
| type = ary.first | |
| name = ary.last | |
| all << Type.new(type, name, type.parameterize, type.underscore.to_sym) | |
| end | |
| end | |
| ALL.each do |t| | |
| # define constant for each type | |
| const_set(t.type.upcase, t.type) | |
| end | |
| def self.all | |
| ALL | |
| end | |
| def self.each(&block) | |
| all.each(&block) | |
| end | |
| def self.find(cond) | |
| cond = { type: cond } if cond.is_a?(String) | |
| cond = cond.first | |
| all.find(Type){ |t| t.send(cond.first) == cond.last } | |
| end | |
| def self.[](cond) | |
| find(cond) | |
| end | |
| def self.to_options | |
| all.map{ |t| [t.name, t.type] } | |
| end | |
| end | |
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment