Sha256: b1df4c3c196a46958d8c68841c5dfadbab6ab7464edf6ad00daab4e435fee9dd

Contents?: true

Size: 1.02 KB

Versions: 2

Compression:

Stored size: 1.02 KB

Contents

require 'forwardable'
require 'cgi'

module RailsTemplatedUrls
  class Builder
    extend Forwardable

    def initialize(name, params, routes)
      @name = name
      @params = params
      @routes = routes

      check_route
    end

    def_delegators :@routes, :named_routes, :url_helpers

    def url
      build(:url)
    end

    def path
      build(:path)
    end

    protected

    def check_route
      return if named_routes.key?(@name)
      fail UnknownRouteError, "Unknown route #{@name.inspect}"
    end

    def required_parts
      named_routes[@name].required_parts
    end

    def required_parts_expressions
      required_parts.map do |key|
        { key => format('{%s}', key) }
      end
    end

    def params_expression
      return if @params.empty?
      format('{?%s}', @params.join(','))
    end

    def build(strategy)
      url = url_helpers.public_send("#{@name}_#{strategy}",
                                    *required_parts_expressions)

      "#{CGI.unescape(url)}#{params_expression}"
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rails_templated_urls-0.1.1 lib/rails_templated_urls/builder.rb
rails_templated_urls-0.1.0 lib/rails_templated_urls/builder.rb