Sha256: 529f7c1059112db3626515fafe0492b65161d0f84fedd014923af6ed154b3ddd

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 KB

Contents

module Galactus
  class Router
    require 'yaml'

    attr_accessor :api_version
    attr_reader :routes

    def initialize(settings = {})
      @routes = {}
      @api_version = settings[:api_version] || 'v1'
      load_api_routes("#{api_version}.yml")
    end

    private

    def load_api_routes(file)
      api_routes_path = check_for_api_file(file)
      contents = YAML.load(File.read(api_routes_path))

      contents.each do |_route_id, route_info|
        add_api_route(route_info['name'], route_info['path'])
      end
    end

    def add_api_route(name, path)
      routes["#{name}_path".to_sym] = { name: name, endpoint: path }
    end

    def check_for_api_file(file)
      script_path = current_script_path
      file_path = File.join(script_path, 'config', file)
      return file_path if File.exist?(file_path)
      file_path = File.join(File.dirname(__FILE__), 'config', file)
      file_path if File.exist?(file_path)
    end

    def current_script_path
      File.expand_path(File.dirname(File.expand_path $PROGRAM_NAME))
    end

    def method_missing(method, *args)
      return unless routes.keys.include?(method)
      endpoint = "#{routes[method][:endpoint]}"
      params = *args

      if params.any?
        params[0].each do |p_key, p_value|
          endpoint.gsub!(":#{p_key}", p_value.to_s)
        end
      end

      "/#{api_version}#{endpoint}"
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
galactus-0.2.0 lib/galactus/router.rb