Module: Urligence

Defined in:
lib/urligence.rb

Instance Method Summary collapse

Instance Method Details

#attach_params(prefix, suffix, *objects) ⇒ Object

Attaches prefix and suffix and appends params



19
20
21
22
# File 'lib/urligence.rb', line 19

def attach_params(prefix, suffix, *objects)
  params = objects.pop if objects.last.is_a?(Hash)
  objects.unshift(prefix).push(suffix).push(params)
end

#hash_for_smart_path(*objects) ⇒ Object



14
15
16
# File 'lib/urligence.rb', line 14

def hash_for_smart_path(*objects)
  urligence *attach_params(:hash_for, :path, *objects)
end

#hash_for_smart_url(*objects) ⇒ Object



10
11
12
# File 'lib/urligence.rb', line 10

def hash_for_smart_url(*objects)
  urligence *attach_params(:hash_for, :url, *objects)
end

#smart_path(*objects) ⇒ Object



6
7
8
# File 'lib/urligence.rb', line 6

def smart_path(*objects)
  urligence *attach_params(nil, :path, *objects)
end

#smart_url(*objects) ⇒ Object



2
3
4
# File 'lib/urligence.rb', line 2

def smart_url(*objects)
  urligence *attach_params(nil, :url, *objects)
end

#urligence(*objects) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/urligence.rb', line 24

def urligence(*objects)
  only_hash = objects.first == :hash_for
  params = {}
  params.merge!(objects.pop) if objects.last.is_a?(Hash)
  
  objects.reject! { |object| object.nil? }
  
  url_fragments = objects.collect do |obj|
    if obj.is_a? Symbol
      obj
    elsif obj.is_a? Array
      obj.first
    else
      obj.class.name.underscore.to_sym
    end
  end
  
  unless only_hash
    send url_fragments.join("_"), *objects.flatten.select { |obj| !obj.is_a? Symbol }.push(params)
  else
    unparsed_params = objects.select { |obj| !obj.is_a? Symbol }
    unparsed_params.each_with_index do |obj, i|
      unless i == (unparsed_params.length-1)
        params.merge!((obj.is_a? Array) ? {"#{obj.first}_id".to_sym => obj[1].to_param} : {"#{obj.class.name.underscore}_id".to_sym => obj.to_param})
      else
        params.merge!((obj.is_a? Array) ? {:id => obj[1].to_param} : {:id => obj.to_param})
      end
    end
    
    send url_fragments.join("_"), params
  end
end