Class: KDL::Types::URLTemplate::Variable

Inherits:
Object
  • Object
show all
Defined in:
lib/kdl/types/url_template.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, limit: nil, explode: false, allow_reserved: false, with_name: false, keep_empties: false) ⇒ Variable

Returns a new instance of Variable.



122
123
124
125
126
127
128
129
# File 'lib/kdl/types/url_template.rb', line 122

def initialize(name, limit: nil, explode: false, allow_reserved: false, with_name: false, keep_empties: false)
  @name = name.to_sym
  @limit = limit
  @explode = explode
  @allow_reserved = allow_reserved
  @with_name = with_name
  @keep_empties = keep_empties
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



120
121
122
# File 'lib/kdl/types/url_template.rb', line 120

def name
  @name
end

Instance Method Details

#encode(string) ⇒ Object



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/kdl/types/url_template.rb', line 167

def encode(string)
  return nil unless string

  string.to_s
        .chars
        .map do |c|
          if UNRESERVED.match?(c) || (@allow_reserved && RESERVED.match?(c))
            c
          else
            IRLReference::Parser.percent_encode(c)
          end
        end
        .join
        .force_encoding('utf-8')
end

#expand(value) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/kdl/types/url_template.rb', line 131

def expand(value)
  if @explode
    case value
    when Array
      value.map { |v| prefix(encode(v)) }
    when Hash
      value.map { |k, v| prefix(encode(v), k) }
    else
      [prefix(encode(value))]
    end
  elsif @limit
    [prefix(limit(value))].compact
  else
    [prefix(flatten(value))].compact
  end
end

#flatten(value) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/kdl/types/url_template.rb', line 154

def flatten(value)
  case value
  when String
    encode(value)
  when Array, Hash
    result = value.to_a
                  .flatten
                  .compact
                  .map { |v| encode(v) }
    result.empty? ? nil : result.join(',')
  end
end

#limit(string) ⇒ Object



148
149
150
151
152
# File 'lib/kdl/types/url_template.rb', line 148

def limit(string)
  return nil unless string

  encode(string[0, @limit])
end

#prefix(string, override = nil) ⇒ Object



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/kdl/types/url_template.rb', line 183

def prefix(string, override = nil)
  return nil unless string

  key = override || @name

  if @with_name || override
    if string.empty? && !@keep_empties
      encode(key)
    else
      "#{encode(key)}=#{string}"
    end
  else
    string
  end
end