Sha256: 2aefcdcf7c0b3caa310a77d54ad02d8ff54b59050dcca91299a9e9e69e2a1855

Contents?: true

Size: 1.06 KB

Versions: 2

Compression:

Stored size: 1.06 KB

Contents

require 'forwardable'
require 'cgi'

module RailsTemplatedUrls
  class Builder
    extend Forwardable

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

      check_route
    end

    def_delegators :@routes, :named_routes

    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.3 lib/rails_templated_urls/builder.rb
rails_templated_urls-0.1.2 lib/rails_templated_urls/builder.rb