Sha256: 866228ae26c00175dfea503172f87b159b43427fac68676247ffc3c82481d64c

Contents?: true

Size: 1.46 KB

Versions: 3

Compression:

Stored size: 1.46 KB

Contents

module Crystal
  class NamedRouter
    attr_accessor :names, :classes
    
    def initialize
      @names, @classes = {}, {}
    end
    
    def add name, klass
      name = name.to_s
      names[name] = klass
      classes[klass] = name
    end
    
    def encode klass, method, params
      if name = classes[klass]
        path = "/#{name}/#{method}"      
        return path, params
      else
        nil
      end
    end
    
    def decode path, params
      parts = path[1..-1].split '/'
      if parts.size >= 2
        method = parts.pop                
        name = parts.join('/')
                        
        if klass = names[name]
          return klass, method, params
        else
          nil
        end
      end
    end  
    
    def encode_route_method method, params = {}
      method = method.sub(/_path$/, '')
      names.each do |name, klass|
        if i = method.rindex(name)
          if method.size == i + name.size and method[(i-1)..(i-1)] == '_'
            return encode(klass, method[0..(i-2)], params)
          end
        end
      end
      raise "Unknown route #{method}!"
    end
    cache_method_with_params :encode_route_method
    
    module Helper
      protected
        def method_missing m, *args, &block
          m = m.to_s
          if m =~ /_path$/
            crystal[:router].routes[:named_router].encode_route_method m, *args
          else
            super m.to_sym, *args, &block
          end
        end
    end
  end
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
crystal-0.0.13 lib/crystal/router/named_router.rb
crystal-0.0.12 lib/crystal/router/named_router.rb
crystal_ext-0.0.11 lib/crystal/router/named_router.rb