Sha256: e54abc59bec45ac5dd60593ca089f30d16202bd3e1a4a9091b143174774e53e3

Contents?: true

Size: 1.2 KB

Versions: 16

Compression:

Stored size: 1.2 KB

Contents

module Paid
  module PathBuilder

    # Take a path like:
    #   ":path/:id/dogs/:dog_id"
    # and convert it to:
    #   "#{object.path}/#{object.id}/dogs/#{params[:id]}" => "/objects/1/dogs/2"
    #
    # Path priority is:
    #   1. Object - this will be a class or an instance of a class.
    #   2. Params - this is a hash of key values. All keys *must* be symbolized.
    def self.build(path, object, params)
      ret = path.dup
      if ret.include?(":")
        matches = ret.scan(/:([^\/]*)/).flatten.map(&:to_sym)
        missing = Set.new(matches)

        matches.each do |match|
          value = determine_value(match, object, params)
          missing.delete(match) unless value.nil?
          ret.sub!(match.inspect, "#{value}")
        end

        if missing.any?
          raise ArgumentError.new("Could not determine the full URL. The following values of the path are missing: #{missing.to_a.join(', ')}. Try setting them in your params.")
        end
      end
      ret
    end

    def self.determine_value(match, object, params)
      value = object.send(match) if object && object.respond_to?(match)
      value ||= params[match] if params && params.has_key?(match)
      value
    end

  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
paid-1.2.1 lib/paid/path_builder.rb
paid-1.2.0 lib/paid/path_builder.rb
paid-1.1.4 lib/paid/path_builder.rb
paid-1.1.3 lib/paid/path_builder.rb
paid-1.1.2 lib/paid/path_builder.rb
paid-1.1.1 lib/paid/path_builder.rb
paid-1.1.0 lib/paid/path_builder.rb
paid-1.0.11 lib/paid/path_builder.rb
paid-1.0.10 lib/paid/path_builder.rb
paid-1.0.9 lib/paid/path_builder.rb
paid-1.0.8 lib/paid/path_builder.rb
paid-1.0.7 lib/paid/path_builder.rb
paid-1.0.6 lib/paid/path_builder.rb
paid-1.0.5 lib/paid/path_builder.rb
paid-1.0.3 lib/paid/path_builder.rb
paid-1.0.2 lib/paid/path_builder.rb