Class: Conjoin::JQuery

Inherits:
Object
  • Object
show all
Defined in:
lib/conjoin/jquery.rb

Constant Summary collapse

JS_ESCAPE =
{ '\\' => '\\\\', '</' => '<\/', "\r\n" => '\n', "\n" => '\n', "\r" => '\n', '"' => '\\"', "'" => "\\'" }

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(selector, options = {}) ⇒ JQuery

Returns a new instance of JQuery.



7
8
9
10
11
12
13
14
15
# File 'lib/conjoin/jquery.rb', line 7

def initialize selector, options = {}
  @html     = ''
  @selector = selector
  @options  = options

  @options.empty? \
    ? @html += "$('#{selector}')" \
    : @html += "$('#{selector}', #{options.to_json})"
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/conjoin/jquery.rb', line 17

def method_missing(m, *args, &block)
  elem = args.first

  case elem
  when JQuery
    content = elem.to_s.chomp(';')
  when String
    content = "'#{escape elem}'"
  when Hash, OpenStruct
    content = elem.to_json
  else
    content = elem
  end

  @html += ".#{m.to_s.camelize(:lower)}(#{content})"

  self
end

Instance Attribute Details

#htmlObject

Returns the value of attribute html.



5
6
7
# File 'lib/conjoin/jquery.rb', line 5

def html
  @html
end

#optionsObject

Returns the value of attribute options.



5
6
7
# File 'lib/conjoin/jquery.rb', line 5

def options
  @options
end

#selectorObject

Returns the value of attribute selector.



5
6
7
# File 'lib/conjoin/jquery.rb', line 5

def selector
  @selector
end

Class Method Details

.escape(js) ⇒ Object



46
47
48
# File 'lib/conjoin/jquery.rb', line 46

def self.escape js
  js.to_s.gsub(/(\\|<\/|\r\n|\\3342\\2200\\2250|[\n\r"'])/) {|match| JS_ESCAPE[match] }
end

Instance Method Details

#escape(js) ⇒ Object



42
43
44
# File 'lib/conjoin/jquery.rb', line 42

def escape js
  Conjoin::JQuery.escape js
end

#to_sObject



36
37
38
39
40
# File 'lib/conjoin/jquery.rb', line 36

def to_s
  return_html = html.dup.to_s
  @html       = "$('#{selector}')"
  "#{return_html};"
end