Module: Humongous::Helpers::SinatraHelpers

Defined in:
lib/humongous/helpers.rb

Instance Method Summary collapse

Instance Method Details

#autanticate!Object



11
12
13
14
15
16
# File 'lib/humongous/helpers.rb', line 11

def autanticate!
  @connection.apply_saved_authentication and return unless @connection.auths.blank?
  return if params[:auth].blank? || params[:auth][:db].blank?
  @connection.add_auth(params[:auth][:db], params[:auth][:username], params[:auth][:password])
  @connection.apply_saved_authentication
end

#connection(params) ⇒ Object



6
7
8
9
# File 'lib/humongous/helpers.rb', line 6

def connection(params)
  opts = opts_to_connect(params)
  session[:connection] = Mongo::Connection.new(opts[:url], opts[:port])
end

#default_optsObject



45
46
47
# File 'lib/humongous/helpers.rb', line 45

def default_opts
  { :skip => 0, :limit => 10 }
end

#doc_to_bson(doc, converter) ⇒ Object



64
65
66
67
68
69
70
71
72
73
# File 'lib/humongous/helpers.rb', line 64

def doc_to_bson( doc, converter )
  doc = send(converter, doc)
  doc.each do |k,v|
    case v
    when Hash
      send(converter, v )
    end
  end
  doc
end

#from_bson(options) ⇒ Object



75
76
77
78
79
80
81
# File 'lib/humongous/helpers.rb', line 75

def from_bson( options )
  ids = options.select{ |k,v| v.is_a? BSON::ObjectId }
  ids.each do | k, v |
    options[k] = v.to_s
  end
  options
end

#get_uri(params = {}) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/humongous/helpers.rb', line 30

def get_uri(params = {})
  @options = {
    :url => "localhost",
    :port => "27017",
    :username => "",
    :password => ""
  }
  @options = @options.merge(params)
  unless @options[:username].empty? && @options[:password].empty?
    "mongodb://#{@options[:username]}:#{@options[:password]}@#{@options[:url]}:#{@options[:port]}"
  else
    "mongodb://#{@options[:url]}:#{@options[:port]}"
  end
end

#json_converter(params_json) ⇒ Object



83
84
85
# File 'lib/humongous/helpers.rb', line 83

def json_converter( params_json )
  params_json.gsub(/(\w+):/, '"\1":')
end

#opts_to_connect(params = {}) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/humongous/helpers.rb', line 18

def opts_to_connect(params = {})
  return @options if @options && @options[:freeze]
  @options = {
    :url => "localhost",
    :port => "27017",
    :username => "",
    :password => ""
  }
  return @options if params.blank?
  @options.merge!({ :url => params[:url], :port => params[:port], :freeze => true })
end

#to_bson(options) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/humongous/helpers.rb', line 49

def to_bson( options )
  ids = options.keys.grep /_id$/
  ids.each do |id|
    begin
      options[id] = BSON::ObjectId.from_string(options[id])
    rescue BSON::InvalidObjectId
      puts "found illegal ObjectId, skipping..."
      next
    rescue e
      puts e.message
    end
  end
  options
end