repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
Everlane/async_cache
lib/async_cache/store.rb
AsyncCache.Store.check_arguments
def check_arguments arguments arguments.each_with_index do |argument, index| next if argument.is_a? Numeric next if argument.is_a? String next if argument.is_a? Symbol next if argument.is_a? Hash next if argument.is_a? NilClass next if argument.is_a? TrueClass next if argument.is_a? FalseClass raise ArgumentError, "Cannot send complex data for block argument #{index + 1}: #{argument.class.name}" end arguments end
ruby
def check_arguments arguments arguments.each_with_index do |argument, index| next if argument.is_a? Numeric next if argument.is_a? String next if argument.is_a? Symbol next if argument.is_a? Hash next if argument.is_a? NilClass next if argument.is_a? TrueClass next if argument.is_a? FalseClass raise ArgumentError, "Cannot send complex data for block argument #{index + 1}: #{argument.class.name}" end arguments end
[ "def", "check_arguments", "arguments", "arguments", ".", "each_with_index", "do", "|", "argument", ",", "index", "|", "next", "if", "argument", ".", "is_a?", "Numeric", "next", "if", "argument", ".", "is_a?", "String", "next", "if", "argument", ".", "is_a?", "Symbol", "next", "if", "argument", ".", "is_a?", "Hash", "next", "if", "argument", ".", "is_a?", "NilClass", "next", "if", "argument", ".", "is_a?", "TrueClass", "next", "if", "argument", ".", "is_a?", "FalseClass", "raise", "ArgumentError", ",", "\"Cannot send complex data for block argument #{index + 1}: #{argument.class.name}\"", "end", "arguments", "end" ]
Ensures the arguments are primitives.
[ "Ensures", "the", "arguments", "are", "primitives", "." ]
68709579b1d3e3bd03ff0afdf01dae32bec767be
https://github.com/Everlane/async_cache/blob/68709579b1d3e3bd03ff0afdf01dae32bec767be/lib/async_cache/store.rb#L153-L167
train
mfdavid/rackstep
lib/router.rb
RackStep.Router.find_route_for
def find_route_for(path, verb) # Ignoring the first char if path starts with '/'. This way the path of # 'http//localhost/' will be the same of 'http://localhost' (both will # be empty strings). path = path[1..-1] if path[0] == '/' route_id = verb + path route = routes[route_id] # If no route was found, set it to 'notfound' route (maintaining the # original verb). route = routes["#{verb}notfound"] if route == nil return route end
ruby
def find_route_for(path, verb) # Ignoring the first char if path starts with '/'. This way the path of # 'http//localhost/' will be the same of 'http://localhost' (both will # be empty strings). path = path[1..-1] if path[0] == '/' route_id = verb + path route = routes[route_id] # If no route was found, set it to 'notfound' route (maintaining the # original verb). route = routes["#{verb}notfound"] if route == nil return route end
[ "def", "find_route_for", "(", "path", ",", "verb", ")", "path", "=", "path", "[", "1", "..", "-", "1", "]", "if", "path", "[", "0", "]", "==", "'/'", "route_id", "=", "verb", "+", "path", "route", "=", "routes", "[", "route_id", "]", "route", "=", "routes", "[", "\"#{verb}notfound\"", "]", "if", "route", "==", "nil", "return", "route", "end" ]
Given a request, will parse it's path to find what it the apropriate controller to respond it.
[ "Given", "a", "request", "will", "parse", "it", "s", "path", "to", "find", "what", "it", "the", "apropriate", "controller", "to", "respond", "it", "." ]
dd0ef8d568dbf46e66e9e3a35eaed59027fe84d3
https://github.com/mfdavid/rackstep/blob/dd0ef8d568dbf46e66e9e3a35eaed59027fe84d3/lib/router.rb#L30-L42
train
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.hide
def hide(name) base_fields[name] = base_fields[name].dup base_fields[name].widget = Widgets::HiddenInput.new end
ruby
def hide(name) base_fields[name] = base_fields[name].dup base_fields[name].widget = Widgets::HiddenInput.new end
[ "def", "hide", "(", "name", ")", "base_fields", "[", "name", "]", "=", "base_fields", "[", "name", "]", ".", "dup", "base_fields", "[", "name", "]", ".", "widget", "=", "Widgets", "::", "HiddenInput", ".", "new", "end" ]
Hide field named +name+
[ "Hide", "field", "named", "+", "name", "+" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L7-L10
train
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.text
def text(name, options = {}) field name, CharField.new(options.merge(widget: Widgets::Textarea.new)) end
ruby
def text(name, options = {}) field name, CharField.new(options.merge(widget: Widgets::Textarea.new)) end
[ "def", "text", "(", "name", ",", "options", "=", "{", "}", ")", "field", "name", ",", "CharField", ".", "new", "(", "options", ".", "merge", "(", "widget", ":", "Widgets", "::", "Textarea", ".", "new", ")", ")", "end" ]
Declare a +CharField+ with text area widget
[ "Declare", "a", "+", "CharField", "+", "with", "text", "area", "widget" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L23-L25
train
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.password
def password(name, options = {}) field name, CharField.new(options.merge(widget: Widgets::PasswordInput.new)) end
ruby
def password(name, options = {}) field name, CharField.new(options.merge(widget: Widgets::PasswordInput.new)) end
[ "def", "password", "(", "name", ",", "options", "=", "{", "}", ")", "field", "name", ",", "CharField", ".", "new", "(", "options", ".", "merge", "(", "widget", ":", "Widgets", "::", "PasswordInput", ".", "new", ")", ")", "end" ]
Declare a +CharField+ with password widget
[ "Declare", "a", "+", "CharField", "+", "with", "password", "widget" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L28-L30
train
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.regex
def regex(name, regexp, options = {}) field name, RegexField.new(regexp, options) end
ruby
def regex(name, regexp, options = {}) field name, RegexField.new(regexp, options) end
[ "def", "regex", "(", "name", ",", "regexp", ",", "options", "=", "{", "}", ")", "field", "name", ",", "RegexField", ".", "new", "(", "regexp", ",", "options", ")", "end" ]
Declare a +RegexField+
[ "Declare", "a", "+", "RegexField", "+" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L43-L45
train
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.choice
def choice(name, choices = [], options = {}) field name, ChoiceField.new(choices, options) end
ruby
def choice(name, choices = [], options = {}) field name, ChoiceField.new(choices, options) end
[ "def", "choice", "(", "name", ",", "choices", "=", "[", "]", ",", "options", "=", "{", "}", ")", "field", "name", ",", "ChoiceField", ".", "new", "(", "choices", ",", "options", ")", "end" ]
Declare a +ChoiceField+ with +choices+
[ "Declare", "a", "+", "ChoiceField", "+", "with", "+", "choices", "+" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L68-L70
train
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.typed_choice
def typed_choice(name, choices = [], options = {}) field name, TypedChoiceField.new(choices, options) end
ruby
def typed_choice(name, choices = [], options = {}) field name, TypedChoiceField.new(choices, options) end
[ "def", "typed_choice", "(", "name", ",", "choices", "=", "[", "]", ",", "options", "=", "{", "}", ")", "field", "name", ",", "TypedChoiceField", ".", "new", "(", "choices", ",", "options", ")", "end" ]
Declare a +TypedChoiceField+ with +choices+
[ "Declare", "a", "+", "TypedChoiceField", "+", "with", "+", "choices", "+" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L73-L75
train
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.multiple_choice
def multiple_choice(name, choices = [], options = {}) field name, MultipleChoiceField.new(choices, options) end
ruby
def multiple_choice(name, choices = [], options = {}) field name, MultipleChoiceField.new(choices, options) end
[ "def", "multiple_choice", "(", "name", ",", "choices", "=", "[", "]", ",", "options", "=", "{", "}", ")", "field", "name", ",", "MultipleChoiceField", ".", "new", "(", "choices", ",", "options", ")", "end" ]
Declare a +MultipleChoiceField+ with +choices+
[ "Declare", "a", "+", "MultipleChoiceField", "+", "with", "+", "choices", "+" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L78-L80
train
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.radio_choice
def radio_choice(name, choices = [], options = {}) field name, ChoiceField.new(choices, options.merge(widget: Widgets::RadioSelect.new)) end
ruby
def radio_choice(name, choices = [], options = {}) field name, ChoiceField.new(choices, options.merge(widget: Widgets::RadioSelect.new)) end
[ "def", "radio_choice", "(", "name", ",", "choices", "=", "[", "]", ",", "options", "=", "{", "}", ")", "field", "name", ",", "ChoiceField", ".", "new", "(", "choices", ",", "options", ".", "merge", "(", "widget", ":", "Widgets", "::", "RadioSelect", ".", "new", ")", ")", "end" ]
Declare a +ChoiceField+ using the +RadioSelect+ widget
[ "Declare", "a", "+", "ChoiceField", "+", "using", "the", "+", "RadioSelect", "+", "widget" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L83-L85
train
tizoc/bureaucrat
lib/bureaucrat/quickfields.rb
Bureaucrat.Quickfields.checkbox_multiple_choice
def checkbox_multiple_choice(name, choices = [], options = {}) field name, MultipleChoiceField.new(choices, options.merge(widget: Widgets::CheckboxSelectMultiple.new)) end
ruby
def checkbox_multiple_choice(name, choices = [], options = {}) field name, MultipleChoiceField.new(choices, options.merge(widget: Widgets::CheckboxSelectMultiple.new)) end
[ "def", "checkbox_multiple_choice", "(", "name", ",", "choices", "=", "[", "]", ",", "options", "=", "{", "}", ")", "field", "name", ",", "MultipleChoiceField", ".", "new", "(", "choices", ",", "options", ".", "merge", "(", "widget", ":", "Widgets", "::", "CheckboxSelectMultiple", ".", "new", ")", ")", "end" ]
Declare a +MultipleChoiceField+ with the +CheckboxSelectMultiple+ widget
[ "Declare", "a", "+", "MultipleChoiceField", "+", "with", "the", "+", "CheckboxSelectMultiple", "+", "widget" ]
0d0778c8477d19030425e0c177ea67dd42ed4e90
https://github.com/tizoc/bureaucrat/blob/0d0778c8477d19030425e0c177ea67dd42ed4e90/lib/bureaucrat/quickfields.rb#L88-L90
train
DannyBen/apicake
lib/apicake/base.rb
APICake.Base.save
def save(filename, path, params={}) payload = get! path, nil, params File.write filename, payload.response.body end
ruby
def save(filename, path, params={}) payload = get! path, nil, params File.write filename, payload.response.body end
[ "def", "save", "(", "filename", ",", "path", ",", "params", "=", "{", "}", ")", "payload", "=", "get!", "path", ",", "nil", ",", "params", "File", ".", "write", "filename", ",", "payload", ".", "response", ".", "body", "end" ]
Save the response body to a file === Example client = Client.new client.save 'out.json', 'some/to/resource', param: value
[ "Save", "the", "response", "body", "to", "a", "file" ]
4b6da01caa798b438e796f6abf97ebd615e4a5bc
https://github.com/DannyBen/apicake/blob/4b6da01caa798b438e796f6abf97ebd615e4a5bc/lib/apicake/base.rb#L170-L173
train
DannyBen/apicake
lib/apicake/base.rb
APICake.Base.csv_node
def csv_node(data) arrays = data.keys.select { |key| data[key].is_a? Array } arrays.empty? ? [data] : data[arrays.first] end
ruby
def csv_node(data) arrays = data.keys.select { |key| data[key].is_a? Array } arrays.empty? ? [data] : data[arrays.first] end
[ "def", "csv_node", "(", "data", ")", "arrays", "=", "data", ".", "keys", ".", "select", "{", "|", "key", "|", "data", "[", "key", "]", ".", "is_a?", "Array", "}", "arrays", ".", "empty?", "?", "[", "data", "]", ":", "data", "[", "arrays", ".", "first", "]", "end" ]
Determins which part of the data is best suited to be displayed as CSV. - If the response contains one or more arrays, the first array will be the CSV output - Otherwise, if the response was parsed to a ruby object, the response itself will be used as a single-row CSV output. Override this if you want to have a different decision process.
[ "Determins", "which", "part", "of", "the", "data", "is", "best", "suited", "to", "be", "displayed", "as", "CSV", "." ]
4b6da01caa798b438e796f6abf97ebd615e4a5bc
https://github.com/DannyBen/apicake/blob/4b6da01caa798b438e796f6abf97ebd615e4a5bc/lib/apicake/base.rb#L222-L225
train
DannyBen/apicake
lib/apicake/base.rb
APICake.Base.http_get
def http_get(path, extra=nil, params={}) payload = self.class.get path, params APICake::Payload.new payload end
ruby
def http_get(path, extra=nil, params={}) payload = self.class.get path, params APICake::Payload.new payload end
[ "def", "http_get", "(", "path", ",", "extra", "=", "nil", ",", "params", "=", "{", "}", ")", "payload", "=", "self", ".", "class", ".", "get", "path", ",", "params", "APICake", "::", "Payload", ".", "new", "payload", "end" ]
Make a call with HTTParty and return a payload object.
[ "Make", "a", "call", "with", "HTTParty", "and", "return", "a", "payload", "object", "." ]
4b6da01caa798b438e796f6abf97ebd615e4a5bc
https://github.com/DannyBen/apicake/blob/4b6da01caa798b438e796f6abf97ebd615e4a5bc/lib/apicake/base.rb#L230-L233
train
DannyBen/apicake
lib/apicake/base.rb
APICake.Base.normalize
def normalize(path, extra=nil, params={}) if extra.is_a?(Hash) and params.empty? params = extra extra = nil end path = "#{path}/#{extra}" if extra path = "/#{path}" unless path[0] == '/' query = default_query.merge params params[:query] = query unless query.empty? params = default_params.merge params [path, extra, params] end
ruby
def normalize(path, extra=nil, params={}) if extra.is_a?(Hash) and params.empty? params = extra extra = nil end path = "#{path}/#{extra}" if extra path = "/#{path}" unless path[0] == '/' query = default_query.merge params params[:query] = query unless query.empty? params = default_params.merge params [path, extra, params] end
[ "def", "normalize", "(", "path", ",", "extra", "=", "nil", ",", "params", "=", "{", "}", ")", "if", "extra", ".", "is_a?", "(", "Hash", ")", "and", "params", ".", "empty?", "params", "=", "extra", "extra", "=", "nil", "end", "path", "=", "\"#{path}/#{extra}\"", "if", "extra", "path", "=", "\"/#{path}\"", "unless", "path", "[", "0", "]", "==", "'/'", "query", "=", "default_query", ".", "merge", "params", "params", "[", ":query", "]", "=", "query", "unless", "query", ".", "empty?", "params", "=", "default_params", ".", "merge", "params", "[", "path", ",", "extra", ",", "params", "]", "end" ]
Normalize the three input parameters
[ "Normalize", "the", "three", "input", "parameters" ]
4b6da01caa798b438e796f6abf97ebd615e4a5bc
https://github.com/DannyBen/apicake/blob/4b6da01caa798b438e796f6abf97ebd615e4a5bc/lib/apicake/base.rb#L236-L251
train
rsim/ruby-plsql
lib/plsql/connection.rb
PLSQL.Connection.describe_synonym
def describe_synonym(schema_name, synonym_name) #:nodoc: select_first( "SELECT table_owner, table_name FROM all_synonyms WHERE owner = :owner AND synonym_name = :synonym_name", schema_name.to_s.upcase, synonym_name.to_s.upcase) end
ruby
def describe_synonym(schema_name, synonym_name) #:nodoc: select_first( "SELECT table_owner, table_name FROM all_synonyms WHERE owner = :owner AND synonym_name = :synonym_name", schema_name.to_s.upcase, synonym_name.to_s.upcase) end
[ "def", "describe_synonym", "(", "schema_name", ",", "synonym_name", ")", "select_first", "(", "\"SELECT table_owner, table_name FROM all_synonyms WHERE owner = :owner AND synonym_name = :synonym_name\"", ",", "schema_name", ".", "to_s", ".", "upcase", ",", "synonym_name", ".", "to_s", ".", "upcase", ")", "end" ]
all_synonyms view is quite slow therefore this implementation is overriden in OCI connection with faster native OCI method
[ "all_synonyms", "view", "is", "quite", "slow", "therefore", "this", "implementation", "is", "overriden", "in", "OCI", "connection", "with", "faster", "native", "OCI", "method" ]
dc5e74200b186ba9e444f75821351aa454f84795
https://github.com/rsim/ruby-plsql/blob/dc5e74200b186ba9e444f75821351aa454f84795/lib/plsql/connection.rb#L184-L188
train
mongoid/moped
lib/moped/connection.rb
Moped.Connection.read
def read with_connection do |socket| reply = Protocol::Reply.allocate data = read_data(socket, 36) response = data.unpack(REPLY_DECODE_STR) reply.length, reply.request_id, reply.response_to, reply.op_code, reply.flags, reply.cursor_id, reply.offset, reply.count = response if reply.count == 0 reply.documents = [] else sock_read = read_data(socket, reply.length - 36) buffer = StringIO.new(sock_read) reply.documents = reply.count.times.map do ::BSON::Document.from_bson(buffer) end end reply end end
ruby
def read with_connection do |socket| reply = Protocol::Reply.allocate data = read_data(socket, 36) response = data.unpack(REPLY_DECODE_STR) reply.length, reply.request_id, reply.response_to, reply.op_code, reply.flags, reply.cursor_id, reply.offset, reply.count = response if reply.count == 0 reply.documents = [] else sock_read = read_data(socket, reply.length - 36) buffer = StringIO.new(sock_read) reply.documents = reply.count.times.map do ::BSON::Document.from_bson(buffer) end end reply end end
[ "def", "read", "with_connection", "do", "|", "socket", "|", "reply", "=", "Protocol", "::", "Reply", ".", "allocate", "data", "=", "read_data", "(", "socket", ",", "36", ")", "response", "=", "data", ".", "unpack", "(", "REPLY_DECODE_STR", ")", "reply", ".", "length", ",", "reply", ".", "request_id", ",", "reply", ".", "response_to", ",", "reply", ".", "op_code", ",", "reply", ".", "flags", ",", "reply", ".", "cursor_id", ",", "reply", ".", "offset", ",", "reply", ".", "count", "=", "response", "if", "reply", ".", "count", "==", "0", "reply", ".", "documents", "=", "[", "]", "else", "sock_read", "=", "read_data", "(", "socket", ",", "reply", ".", "length", "-", "36", ")", "buffer", "=", "StringIO", ".", "new", "(", "sock_read", ")", "reply", ".", "documents", "=", "reply", ".", "count", ".", "times", ".", "map", "do", "::", "BSON", "::", "Document", ".", "from_bson", "(", "buffer", ")", "end", "end", "reply", "end", "end" ]
Initialize the connection. @example Initialize the connection. Connection.new("localhost", 27017, 5) @param [ String ] host The host to connect to. @param [ Integer ] post The server port. @param [ Integer ] timeout The connection timeout. @param [ Hash ] options Options for the connection. @option options [ Boolean ] :ssl Connect using SSL @since 1.0.0 Read from the connection. @example Read from the connection. connection.read @return [ Hash ] The returned document. @since 1.0.0
[ "Initialize", "the", "connection", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/connection.rb#L114-L139
train
mongoid/moped
lib/moped/connection.rb
Moped.Connection.write
def write(operations) buf = "" operations.each do |operation| operation.request_id = (@request_id += 1) operation.serialize(buf) end with_connection do |socket| socket.write(buf) end end
ruby
def write(operations) buf = "" operations.each do |operation| operation.request_id = (@request_id += 1) operation.serialize(buf) end with_connection do |socket| socket.write(buf) end end
[ "def", "write", "(", "operations", ")", "buf", "=", "\"\"", "operations", ".", "each", "do", "|", "operation", "|", "operation", ".", "request_id", "=", "(", "@request_id", "+=", "1", ")", "operation", ".", "serialize", "(", "buf", ")", "end", "with_connection", "do", "|", "socket", "|", "socket", ".", "write", "(", "buf", ")", "end", "end" ]
Write to the connection. @example Write to the connection. connection.write(data) @param [ Array<Message> ] operations The database operations. @return [ Integer ] The number of bytes written. @since 1.0.0
[ "Write", "to", "the", "connection", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/connection.rb#L167-L176
train
mongoid/moped
lib/moped/connection.rb
Moped.Connection.read_data
def read_data(socket, length) data = socket.read(length) unless data raise Errors::ConnectionFailure.new( "Attempted to read #{length} bytes from the socket but nothing was returned." ) end if data.length < length data << read_data(socket, length - data.length) end data end
ruby
def read_data(socket, length) data = socket.read(length) unless data raise Errors::ConnectionFailure.new( "Attempted to read #{length} bytes from the socket but nothing was returned." ) end if data.length < length data << read_data(socket, length - data.length) end data end
[ "def", "read_data", "(", "socket", ",", "length", ")", "data", "=", "socket", ".", "read", "(", "length", ")", "unless", "data", "raise", "Errors", "::", "ConnectionFailure", ".", "new", "(", "\"Attempted to read #{length} bytes from the socket but nothing was returned.\"", ")", "end", "if", "data", ".", "length", "<", "length", "data", "<<", "read_data", "(", "socket", ",", "length", "-", "data", ".", "length", ")", "end", "data", "end" ]
Read data from the socket until we get back the number of bytes that we are expecting. @api private @example Read the number of bytes. connection.read_data(socket, 36) @param [ TCPSocket ] socket The socket to read from. @param [ Integer ] length The number of bytes to read. @return [ String ] The read data. @since 1.2.9
[ "Read", "data", "from", "the", "socket", "until", "we", "get", "back", "the", "number", "of", "bytes", "that", "we", "are", "expecting", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/connection.rb#L194-L205
train
mongoid/moped
lib/moped/node.rb
Moped.Node.command
def command(database, cmd, options = {}) read(Protocol::Command.new(database, cmd, options)) end
ruby
def command(database, cmd, options = {}) read(Protocol::Command.new(database, cmd, options)) end
[ "def", "command", "(", "database", ",", "cmd", ",", "options", "=", "{", "}", ")", "read", "(", "Protocol", "::", "Command", ".", "new", "(", "database", ",", "cmd", ",", "options", ")", ")", "end" ]
Execute a command against a database. @example Execute a command. node.command(database, { ping: 1 }) @param [ Database ] database The database to run the command on. @param [ Hash ] cmd The command to execute. @options [ Hash ] options The command options. @raise [ OperationFailure ] If the command failed. @return [ Hash ] The result of the command. @since 1.0.0
[ "Execute", "a", "command", "against", "a", "database", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L89-L91
train
mongoid/moped
lib/moped/node.rb
Moped.Node.connection
def connection connection_acquired = false begin pool.with do |conn| connection_acquired = true yield(conn) end rescue Timeout::Error, ConnectionPool::PoolShuttingDownError => e if e.kind_of?(ConnectionPool::PoolShuttingDownError) @pool = nil Connection::Manager.delete_pool(self) raise Errors::PoolTimeout.new(e) end raise connection_acquired ? e : Errors::PoolTimeout.new(e) end end
ruby
def connection connection_acquired = false begin pool.with do |conn| connection_acquired = true yield(conn) end rescue Timeout::Error, ConnectionPool::PoolShuttingDownError => e if e.kind_of?(ConnectionPool::PoolShuttingDownError) @pool = nil Connection::Manager.delete_pool(self) raise Errors::PoolTimeout.new(e) end raise connection_acquired ? e : Errors::PoolTimeout.new(e) end end
[ "def", "connection", "connection_acquired", "=", "false", "begin", "pool", ".", "with", "do", "|", "conn", "|", "connection_acquired", "=", "true", "yield", "(", "conn", ")", "end", "rescue", "Timeout", "::", "Error", ",", "ConnectionPool", "::", "PoolShuttingDownError", "=>", "e", "if", "e", ".", "kind_of?", "(", "ConnectionPool", "::", "PoolShuttingDownError", ")", "@pool", "=", "nil", "Connection", "::", "Manager", ".", "delete_pool", "(", "self", ")", "raise", "Errors", "::", "PoolTimeout", ".", "new", "(", "e", ")", "end", "raise", "connection_acquired", "?", "e", ":", "Errors", "::", "PoolTimeout", ".", "new", "(", "e", ")", "end", "end" ]
Get the underlying connection for the node. @example Get the node's connection. node.connection @return [ Connection ] The connection. @since 2.0.0
[ "Get", "the", "underlying", "connection", "for", "the", "node", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L113-L128
train
mongoid/moped
lib/moped/node.rb
Moped.Node.ensure_connected
def ensure_connected(&block) unless (conn = stack(:connection)).empty? return yield(conn.first) end begin connection do |conn| connect(conn) unless conn.alive? conn.apply_credentials(@credentials) stack(:connection) << conn yield(conn) end rescue Exception => e if e.kind_of?(ConnectionPool::PoolShuttingDownError) @pool = nil Connection::Manager.delete_pool(self) end Failover.get(e).execute(e, self, &block) ensure end_execution(:connection) end end
ruby
def ensure_connected(&block) unless (conn = stack(:connection)).empty? return yield(conn.first) end begin connection do |conn| connect(conn) unless conn.alive? conn.apply_credentials(@credentials) stack(:connection) << conn yield(conn) end rescue Exception => e if e.kind_of?(ConnectionPool::PoolShuttingDownError) @pool = nil Connection::Manager.delete_pool(self) end Failover.get(e).execute(e, self, &block) ensure end_execution(:connection) end end
[ "def", "ensure_connected", "(", "&", "block", ")", "unless", "(", "conn", "=", "stack", "(", ":connection", ")", ")", ".", "empty?", "return", "yield", "(", "conn", ".", "first", ")", "end", "begin", "connection", "do", "|", "conn", "|", "connect", "(", "conn", ")", "unless", "conn", ".", "alive?", "conn", ".", "apply_credentials", "(", "@credentials", ")", "stack", "(", ":connection", ")", "<<", "conn", "yield", "(", "conn", ")", "end", "rescue", "Exception", "=>", "e", "if", "e", ".", "kind_of?", "(", "ConnectionPool", "::", "PoolShuttingDownError", ")", "@pool", "=", "nil", "Connection", "::", "Manager", ".", "delete_pool", "(", "self", ")", "end", "Failover", ".", "get", "(", "e", ")", ".", "execute", "(", "e", ",", "self", ",", "&", "block", ")", "ensure", "end_execution", "(", ":connection", ")", "end", "end" ]
Yields the block if a connection can be established, retrying when a connection error is raised. @example Ensure we are connection. node.ensure_connected do #... end @raises [ ConnectionFailure ] When a connection cannot be established. @return [ nil ] nil. @since 1.0.0
[ "Yields", "the", "block", "if", "a", "connection", "can", "be", "established", "retrying", "when", "a", "connection", "error", "is", "raised", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L183-L204
train
mongoid/moped
lib/moped/node.rb
Moped.Node.get_more
def get_more(database, collection, cursor_id, limit) read(Protocol::GetMore.new(database, collection, cursor_id, limit)) end
ruby
def get_more(database, collection, cursor_id, limit) read(Protocol::GetMore.new(database, collection, cursor_id, limit)) end
[ "def", "get_more", "(", "database", ",", "collection", ",", "cursor_id", ",", "limit", ")", "read", "(", "Protocol", "::", "GetMore", ".", "new", "(", "database", ",", "collection", ",", "cursor_id", ",", "limit", ")", ")", "end" ]
Execute a get more operation on the node. @example Execute a get more. node.get_more(database, collection, 12345, -1) @param [ Database ] database The database to get more from. @param [ Collection ] collection The collection to get more from. @param [ Integer ] cursor_id The id of the cursor on the server. @param [ Integer ] limit The number of documents to limit. @raise [ CursorNotFound ] if the cursor has been killed @return [ Message ] The result of the operation. @since 1.0.0
[ "Execute", "a", "get", "more", "operation", "on", "the", "node", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L237-L239
train
mongoid/moped
lib/moped/node.rb
Moped.Node.insert
def insert(database, collection, documents, concern, options = {}) write(Protocol::Insert.new(database, collection, documents, options), concern) end
ruby
def insert(database, collection, documents, concern, options = {}) write(Protocol::Insert.new(database, collection, documents, options), concern) end
[ "def", "insert", "(", "database", ",", "collection", ",", "documents", ",", "concern", ",", "options", "=", "{", "}", ")", "write", "(", "Protocol", "::", "Insert", ".", "new", "(", "database", ",", "collection", ",", "documents", ",", "options", ")", ",", "concern", ")", "end" ]
Get the hash identifier for the node. @example Get the hash identifier. node.hash @return [ Integer ] The hash identifier. @since 1.0.0 Creat the new node. @example Create the new node. Node.new("127.0.0.1:27017") @param [ String ] address The location of the server node. @param [ Hash ] options Additional options for the node (ssl) @since 1.0.0 Insert documents into the database. @example Insert documents. node.insert(database, collection, [{ name: "Tool" }]) @param [ Database ] database The database to insert to. @param [ Collection ] collection The collection to insert to. @param [ Array<Hash> ] documents The documents to insert. @return [ Message ] The result of the operation. @since 1.0.0
[ "Get", "the", "hash", "identifier", "for", "the", "node", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L287-L289
train
mongoid/moped
lib/moped/node.rb
Moped.Node.process
def process(operation, &callback) if executing?(:pipeline) queue.push([ operation, callback ]) else flush([[ operation, callback ]]) end end
ruby
def process(operation, &callback) if executing?(:pipeline) queue.push([ operation, callback ]) else flush([[ operation, callback ]]) end end
[ "def", "process", "(", "operation", ",", "&", "callback", ")", "if", "executing?", "(", ":pipeline", ")", "queue", ".", "push", "(", "[", "operation", ",", "callback", "]", ")", "else", "flush", "(", "[", "[", "operation", ",", "callback", "]", "]", ")", "end", "end" ]
Processes the provided operation on this node, and will execute the callback when the operation is sent to the database. @example Process a read operation. node.process(query) do |reply| return reply.documents end @param [ Message ] operation The database operation. @param [ Proc ] callback The callback to run on operation completion. @return [ Object ] The result of the callback. @since 1.0.0
[ "Processes", "the", "provided", "operation", "on", "this", "node", "and", "will", "execute", "the", "callback", "when", "the", "operation", "is", "sent", "to", "the", "database", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L402-L408
train
mongoid/moped
lib/moped/node.rb
Moped.Node.query
def query(database, collection, selector, options = {}) read(Protocol::Query.new(database, collection, selector, options)) end
ruby
def query(database, collection, selector, options = {}) read(Protocol::Query.new(database, collection, selector, options)) end
[ "def", "query", "(", "database", ",", "collection", ",", "selector", ",", "options", "=", "{", "}", ")", "read", "(", "Protocol", "::", "Query", ".", "new", "(", "database", ",", "collection", ",", "selector", ",", "options", ")", ")", "end" ]
Execute a query on the node. @example Execute a query. node.query(database, collection, { name: "Tool" }) @param [ Database ] database The database to query from. @param [ Collection ] collection The collection to query from. @param [ Hash ] selector The query selector. @param [ Hash ] options The query options. @raise [ QueryFailure ] If the query had an error. @return [ Message ] The result of the operation. @since 1.0.0
[ "Execute", "a", "query", "on", "the", "node", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L425-L427
train
mongoid/moped
lib/moped/node.rb
Moped.Node.refresh
def refresh if address.resolve(self) begin @refreshed_at = Time.now configure(command("admin", ismaster: 1)) if !primary? && executing?(:ensure_primary) raise Errors::ReplicaSetReconfigured.new("#{inspect} is no longer the primary node.", {}) elsif !messagable? # not primary or secondary so mark it as down, since it's probably # a recovering node withing the replica set down! end rescue Timeout::Error down! end end end
ruby
def refresh if address.resolve(self) begin @refreshed_at = Time.now configure(command("admin", ismaster: 1)) if !primary? && executing?(:ensure_primary) raise Errors::ReplicaSetReconfigured.new("#{inspect} is no longer the primary node.", {}) elsif !messagable? # not primary or secondary so mark it as down, since it's probably # a recovering node withing the replica set down! end rescue Timeout::Error down! end end end
[ "def", "refresh", "if", "address", ".", "resolve", "(", "self", ")", "begin", "@refreshed_at", "=", "Time", ".", "now", "configure", "(", "command", "(", "\"admin\"", ",", "ismaster", ":", "1", ")", ")", "if", "!", "primary?", "&&", "executing?", "(", ":ensure_primary", ")", "raise", "Errors", "::", "ReplicaSetReconfigured", ".", "new", "(", "\"#{inspect} is no longer the primary node.\"", ",", "{", "}", ")", "elsif", "!", "messagable?", "down!", "end", "rescue", "Timeout", "::", "Error", "down!", "end", "end", "end" ]
Refresh information about the node, such as it's status in the replica set and it's known peers. @example Refresh the node. node.refresh @raise [ ConnectionFailure ] If the node cannot be reached. @raise [ ReplicaSetReconfigured ] If the node is no longer a primary node and refresh was called within an +#ensure_primary+ block. @return [ nil ] nil. @since 1.0.0
[ "Refresh", "information", "about", "the", "node", "such", "as", "it", "s", "status", "in", "the", "replica", "set", "and", "it", "s", "known", "peers", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L443-L459
train
mongoid/moped
lib/moped/node.rb
Moped.Node.remove
def remove(database, collection, selector, concern, options = {}) write(Protocol::Delete.new(database, collection, selector, options), concern) end
ruby
def remove(database, collection, selector, concern, options = {}) write(Protocol::Delete.new(database, collection, selector, options), concern) end
[ "def", "remove", "(", "database", ",", "collection", ",", "selector", ",", "concern", ",", "options", "=", "{", "}", ")", "write", "(", "Protocol", "::", "Delete", ".", "new", "(", "database", ",", "collection", ",", "selector", ",", "options", ")", ",", "concern", ")", "end" ]
Execute a remove command for the provided selector. @example Remove documents. node.remove(database, collection, { name: "Tool" }) @param [ Database ] database The database to remove from. @param [ Collection ] collection The collection to remove from. @param [ Hash ] selector The query selector. @param [ Hash ] options The remove options. @return [ Message ] The result of the operation. @since 1.0.0
[ "Execute", "a", "remove", "command", "for", "the", "provided", "selector", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L474-L476
train
mongoid/moped
lib/moped/node.rb
Moped.Node.update
def update(database, collection, selector, change, concern, options = {}) write(Protocol::Update.new(database, collection, selector, change, options), concern) end
ruby
def update(database, collection, selector, change, concern, options = {}) write(Protocol::Update.new(database, collection, selector, change, options), concern) end
[ "def", "update", "(", "database", ",", "collection", ",", "selector", ",", "change", ",", "concern", ",", "options", "=", "{", "}", ")", "write", "(", "Protocol", "::", "Update", ".", "new", "(", "database", ",", "collection", ",", "selector", ",", "change", ",", "options", ")", ",", "concern", ")", "end" ]
Execute an update command for the provided selector. @example Update documents. node.update(database, collection, { name: "Tool" }, { likes: 1000 }) @param [ Database ] database The database to update. @param [ Collection ] collection The collection to update. @param [ Hash ] selector The query selector. @param [ Hash ] change The updates. @param [ Hash ] options The update options. @return [ Message ] The result of the operation. @since 1.0.0
[ "Execute", "an", "update", "command", "for", "the", "provided", "selector", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L516-L518
train
mongoid/moped
lib/moped/node.rb
Moped.Node.connect
def connect(conn) start = Time.now conn.connect @latency = Time.now - start @down_at = nil true end
ruby
def connect(conn) start = Time.now conn.connect @latency = Time.now - start @down_at = nil true end
[ "def", "connect", "(", "conn", ")", "start", "=", "Time", ".", "now", "conn", ".", "connect", "@latency", "=", "Time", ".", "now", "-", "start", "@down_at", "=", "nil", "true", "end" ]
Connect the node on the underlying connection. @example Connect the node. node.connect @raise [ Errors::ConnectionFailure ] If connection failed. @return [ true ] If the connection suceeded. @since 2.0.0
[ "Connect", "the", "node", "on", "the", "underlying", "connection", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L544-L550
train
mongoid/moped
lib/moped/node.rb
Moped.Node.discover
def discover(*nodes) nodes.flatten.compact.each do |peer| node = Node.new(peer, options) node.credentials.merge!(@credentials) peers.push(node) unless peers.include?(node) end end
ruby
def discover(*nodes) nodes.flatten.compact.each do |peer| node = Node.new(peer, options) node.credentials.merge!(@credentials) peers.push(node) unless peers.include?(node) end end
[ "def", "discover", "(", "*", "nodes", ")", "nodes", ".", "flatten", ".", "compact", ".", "each", "do", "|", "peer", "|", "node", "=", "Node", ".", "new", "(", "peer", ",", "options", ")", "node", ".", "credentials", ".", "merge!", "(", "@credentials", ")", "peers", ".", "push", "(", "node", ")", "unless", "peers", ".", "include?", "(", "node", ")", "end", "end" ]
Discover the additional nodes. @api private @example Discover the additional nodes. node.discover([ "127.0.0.1:27019" ]) @param [ Array<String> ] nodes The new nodes. @since 2.0.0
[ "Discover", "the", "additional", "nodes", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L580-L586
train
mongoid/moped
lib/moped/node.rb
Moped.Node.flush
def flush(ops = queue) operations, callbacks = ops.transpose logging(operations) do ensure_connected do |conn| conn.write(operations) replies = conn.receive_replies(operations) replies.zip(callbacks).map do |reply, callback| callback ? callback[reply] : reply end.last end end ensure ops.clear end
ruby
def flush(ops = queue) operations, callbacks = ops.transpose logging(operations) do ensure_connected do |conn| conn.write(operations) replies = conn.receive_replies(operations) replies.zip(callbacks).map do |reply, callback| callback ? callback[reply] : reply end.last end end ensure ops.clear end
[ "def", "flush", "(", "ops", "=", "queue", ")", "operations", ",", "callbacks", "=", "ops", ".", "transpose", "logging", "(", "operations", ")", "do", "ensure_connected", "do", "|", "conn", "|", "conn", ".", "write", "(", "operations", ")", "replies", "=", "conn", ".", "receive_replies", "(", "operations", ")", "replies", ".", "zip", "(", "callbacks", ")", ".", "map", "do", "|", "reply", ",", "callback", "|", "callback", "?", "callback", "[", "reply", "]", ":", "reply", "end", ".", "last", "end", "end", "ensure", "ops", ".", "clear", "end" ]
Flush the node operations to the database. @api private @example Flush the operations. node.flush([ command ]) @param [ Array<Message> ] ops The operations to flush. @return [ Object ] The result of the operations. @since 2.0.0
[ "Flush", "the", "node", "operations", "to", "the", "database", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/node.rb#L600-L614
train
mongoid/moped
spec/support/replica_set_simulator.rb
Support.ReplicaSetSimulator.start
def start @nodes.each(&:start) @worker = Thread.start do Thread.abort_on_exception = true catch(:shutdown) do loop do Moped.logger.debug "replica_set: waiting for next client" server, client = @manager.next_client if server Moped.logger.debug "replica_set: proxying incoming request to mongo" server.proxy(client, @mongo) else Moped.logger.debug "replica_set: no requests; passing" Thread.pass end end end end end
ruby
def start @nodes.each(&:start) @worker = Thread.start do Thread.abort_on_exception = true catch(:shutdown) do loop do Moped.logger.debug "replica_set: waiting for next client" server, client = @manager.next_client if server Moped.logger.debug "replica_set: proxying incoming request to mongo" server.proxy(client, @mongo) else Moped.logger.debug "replica_set: no requests; passing" Thread.pass end end end end end
[ "def", "start", "@nodes", ".", "each", "(", "&", ":start", ")", "@worker", "=", "Thread", ".", "start", "do", "Thread", ".", "abort_on_exception", "=", "true", "catch", "(", ":shutdown", ")", "do", "loop", "do", "Moped", ".", "logger", ".", "debug", "\"replica_set: waiting for next client\"", "server", ",", "client", "=", "@manager", ".", "next_client", "if", "server", "Moped", ".", "logger", ".", "debug", "\"replica_set: proxying incoming request to mongo\"", "server", ".", "proxy", "(", "client", ",", "@mongo", ")", "else", "Moped", ".", "logger", ".", "debug", "\"replica_set: no requests; passing\"", "Thread", ".", "pass", "end", "end", "end", "end", "end" ]
Start the mock replica set.
[ "Start", "the", "mock", "replica", "set", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/spec/support/replica_set_simulator.rb#L63-L82
train
mongoid/moped
spec/support/replica_set_simulator.rb
Support.ReplicaSetSimulator.initiate
def initiate primary, *secondaries = @nodes.shuffle primary.promote secondaries.each(&:demote) return primary, secondaries end
ruby
def initiate primary, *secondaries = @nodes.shuffle primary.promote secondaries.each(&:demote) return primary, secondaries end
[ "def", "initiate", "primary", ",", "*", "secondaries", "=", "@nodes", ".", "shuffle", "primary", ".", "promote", "secondaries", ".", "each", "(", "&", ":demote", ")", "return", "primary", ",", "secondaries", "end" ]
Pick a node to be master, and mark the rest as secondary
[ "Pick", "a", "node", "to", "be", "master", "and", "mark", "the", "rest", "as", "secondary" ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/spec/support/replica_set_simulator.rb#L85-L92
train
mongoid/moped
lib/moped/cluster.rb
Moped.Cluster.nodes
def nodes # Find the nodes that were down but are ready to be refreshed, or those # with stale connection information. needs_refresh, available = seeds.partition do |node| refreshable?(node) end # Refresh those nodes. available.concat(refresh(needs_refresh)) # Now return all the nodes that are available and participating in the # replica set. available.reject{ |node| node.down? } end
ruby
def nodes # Find the nodes that were down but are ready to be refreshed, or those # with stale connection information. needs_refresh, available = seeds.partition do |node| refreshable?(node) end # Refresh those nodes. available.concat(refresh(needs_refresh)) # Now return all the nodes that are available and participating in the # replica set. available.reject{ |node| node.down? } end
[ "def", "nodes", "needs_refresh", ",", "available", "=", "seeds", ".", "partition", "do", "|", "node", "|", "refreshable?", "(", "node", ")", "end", "available", ".", "concat", "(", "refresh", "(", "needs_refresh", ")", ")", "available", ".", "reject", "{", "|", "node", "|", "node", ".", "down?", "}", "end" ]
Returns the list of available nodes, refreshing 1) any nodes which were down and ready to be checked again and 2) any nodes whose information is out of date. Arbiter nodes are not returned. @example Get the available nodes. cluster.nodes @return [ Array<Node> ] the list of available nodes. @since 1.0.0
[ "Returns", "the", "list", "of", "available", "nodes", "refreshing", "1", ")", "any", "nodes", "which", "were", "down", "and", "ready", "to", "be", "checked", "again", "and", "2", ")", "any", "nodes", "whose", "information", "is", "out", "of", "date", ".", "Arbiter", "nodes", "are", "not", "returned", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/cluster.rb#L143-L156
train
mongoid/moped
lib/moped/cluster.rb
Moped.Cluster.refresh
def refresh(nodes_to_refresh = seeds) refreshed_nodes = [] seen = {} # Set up a recursive lambda function for refreshing a node and it's peers. refresh_node = ->(node) do unless node.address.resolved begin node.refresh rescue Errors::ConnectionFailure end end unless seen[node] || !node.address.resolved seen[node] = true # Add the node to the global list of known nodes. seeds.push(node) unless seeds.include?(node) begin node.refresh # This node is good, so add it to the list of nodes to return. refreshed_nodes.push(node) unless refreshed_nodes.include?(node) # Now refresh any newly discovered peer nodes - this will also # remove nodes that are not included in the peer list. refresh_peers(node, &refresh_node) rescue Errors::ConnectionFailure # We couldn't connect to the node. end end end nodes_to_refresh.each(&refresh_node) refreshed_nodes end
ruby
def refresh(nodes_to_refresh = seeds) refreshed_nodes = [] seen = {} # Set up a recursive lambda function for refreshing a node and it's peers. refresh_node = ->(node) do unless node.address.resolved begin node.refresh rescue Errors::ConnectionFailure end end unless seen[node] || !node.address.resolved seen[node] = true # Add the node to the global list of known nodes. seeds.push(node) unless seeds.include?(node) begin node.refresh # This node is good, so add it to the list of nodes to return. refreshed_nodes.push(node) unless refreshed_nodes.include?(node) # Now refresh any newly discovered peer nodes - this will also # remove nodes that are not included in the peer list. refresh_peers(node, &refresh_node) rescue Errors::ConnectionFailure # We couldn't connect to the node. end end end nodes_to_refresh.each(&refresh_node) refreshed_nodes end
[ "def", "refresh", "(", "nodes_to_refresh", "=", "seeds", ")", "refreshed_nodes", "=", "[", "]", "seen", "=", "{", "}", "refresh_node", "=", "->", "(", "node", ")", "do", "unless", "node", ".", "address", ".", "resolved", "begin", "node", ".", "refresh", "rescue", "Errors", "::", "ConnectionFailure", "end", "end", "unless", "seen", "[", "node", "]", "||", "!", "node", ".", "address", ".", "resolved", "seen", "[", "node", "]", "=", "true", "seeds", ".", "push", "(", "node", ")", "unless", "seeds", ".", "include?", "(", "node", ")", "begin", "node", ".", "refresh", "refreshed_nodes", ".", "push", "(", "node", ")", "unless", "refreshed_nodes", ".", "include?", "(", "node", ")", "refresh_peers", "(", "node", ",", "&", "refresh_node", ")", "rescue", "Errors", "::", "ConnectionFailure", "end", "end", "end", "nodes_to_refresh", ".", "each", "(", "&", "refresh_node", ")", "refreshed_nodes", "end" ]
Refreshes information for each of the nodes provided. The node list defaults to the list of all known nodes. If a node is successfully refreshed, any newly discovered peers will also be refreshed. @example Refresh the nodes. cluster.refresh @param [ Array<Node> ] nodes_to_refresh The nodes to refresh. @return [ Array<Node> ] the available nodes @since 1.0.0
[ "Refreshes", "information", "for", "each", "of", "the", "nodes", "provided", ".", "The", "node", "list", "defaults", "to", "the", "list", "of", "all", "known", "nodes", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/cluster.rb#L172-L202
train
mongoid/moped
lib/moped/cluster.rb
Moped.Cluster.with_primary
def with_primary(&block) if node = nodes.find(&:primary?) begin node.ensure_primary do return yield(node) end rescue Errors::ConnectionFailure, Errors::ReplicaSetReconfigured end end raise Errors::ConnectionFailure, "Could not connect to a primary node for replica set #{inspect}" end
ruby
def with_primary(&block) if node = nodes.find(&:primary?) begin node.ensure_primary do return yield(node) end rescue Errors::ConnectionFailure, Errors::ReplicaSetReconfigured end end raise Errors::ConnectionFailure, "Could not connect to a primary node for replica set #{inspect}" end
[ "def", "with_primary", "(", "&", "block", ")", "if", "node", "=", "nodes", ".", "find", "(", "&", ":primary?", ")", "begin", "node", ".", "ensure_primary", "do", "return", "yield", "(", "node", ")", "end", "rescue", "Errors", "::", "ConnectionFailure", ",", "Errors", "::", "ReplicaSetReconfigured", "end", "end", "raise", "Errors", "::", "ConnectionFailure", ",", "\"Could not connect to a primary node for replica set #{inspect}\"", "end" ]
Yields the replica set's primary node to the provided block. This method will retry the block in case of connection errors or replica set reconfiguration. @example Yield the primary to the block. cluster.with_primary do |node| # ... end @param [ Integer ] retries The number of times to retry. @raises [ ConnectionFailure ] When no primary node can be found @return [ Object ] The result of the yield. @since 1.0.0
[ "Yields", "the", "replica", "set", "s", "primary", "node", "to", "the", "provided", "block", ".", "This", "method", "will", "retry", "the", "block", "in", "case", "of", "connection", "errors", "or", "replica", "set", "reconfiguration", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/cluster.rb#L245-L255
train
mongoid/moped
lib/moped/cluster.rb
Moped.Cluster.with_secondary
def with_secondary(&block) available_nodes = available_secondary_nodes while node = available_nodes.shift begin return yield(node) rescue Errors::ConnectionFailure, Errors::ReplicaSetReconfigured => e next end end raise Errors::ConnectionFailure, "Could not connect to a secondary node for replica set #{inspect}" end
ruby
def with_secondary(&block) available_nodes = available_secondary_nodes while node = available_nodes.shift begin return yield(node) rescue Errors::ConnectionFailure, Errors::ReplicaSetReconfigured => e next end end raise Errors::ConnectionFailure, "Could not connect to a secondary node for replica set #{inspect}" end
[ "def", "with_secondary", "(", "&", "block", ")", "available_nodes", "=", "available_secondary_nodes", "while", "node", "=", "available_nodes", ".", "shift", "begin", "return", "yield", "(", "node", ")", "rescue", "Errors", "::", "ConnectionFailure", ",", "Errors", "::", "ReplicaSetReconfigured", "=>", "e", "next", "end", "end", "raise", "Errors", "::", "ConnectionFailure", ",", "\"Could not connect to a secondary node for replica set #{inspect}\"", "end" ]
Yields a secondary node if available, otherwise the primary node. This method will retry the block in case of connection errors. @example Yield the secondary to the block. cluster.with_secondary do |node| # ... end @param [ Integer ] retries The number of times to retry. @raises [ ConnectionFailure ] When no primary node can be found @return [ Object ] The result of the yield. @since 1.0.0
[ "Yields", "a", "secondary", "node", "if", "available", "otherwise", "the", "primary", "node", ".", "This", "method", "will", "retry", "the", "block", "in", "case", "of", "connection", "errors", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/cluster.rb#L272-L282
train
mongoid/moped
lib/moped/cluster.rb
Moped.Cluster.refreshable?
def refreshable?(node) return false if node.arbiter? node.down? ? node.down_at < down_boundary : node.needs_refresh?(refresh_boundary) end
ruby
def refreshable?(node) return false if node.arbiter? node.down? ? node.down_at < down_boundary : node.needs_refresh?(refresh_boundary) end
[ "def", "refreshable?", "(", "node", ")", "return", "false", "if", "node", ".", "arbiter?", "node", ".", "down?", "?", "node", ".", "down_at", "<", "down_boundary", ":", "node", ".", "needs_refresh?", "(", "refresh_boundary", ")", "end" ]
Is the provided node refreshable? This is in the case where the refresh boundary has passed, or the node has been down longer than the down boundary. @api private @example Is the node refreshable? cluster.refreshable?(node) @param [ Node ] node The Node to check. @since 2.0.0
[ "Is", "the", "provided", "node", "refreshable?", "This", "is", "in", "the", "case", "where", "the", "refresh", "boundary", "has", "passed", "or", "the", "node", "has", "been", "down", "longer", "than", "the", "down", "boundary", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/cluster.rb#L347-L350
train
mongoid/moped
lib/moped/cluster.rb
Moped.Cluster.refresh_peers
def refresh_peers(node, &block) node.peers.each do |node| if node.address.resolved block.call(node) unless seeds.include?(node) peers.push(node) unless peers.include?(node) end end end
ruby
def refresh_peers(node, &block) node.peers.each do |node| if node.address.resolved block.call(node) unless seeds.include?(node) peers.push(node) unless peers.include?(node) end end end
[ "def", "refresh_peers", "(", "node", ",", "&", "block", ")", "node", ".", "peers", ".", "each", "do", "|", "node", "|", "if", "node", ".", "address", ".", "resolved", "block", ".", "call", "(", "node", ")", "unless", "seeds", ".", "include?", "(", "node", ")", "peers", ".", "push", "(", "node", ")", "unless", "peers", ".", "include?", "(", "node", ")", "end", "end", "end" ]
Refresh the peers based on the node's peers. @api private @example Refresh the peers. cluster.refresh_peers(node) @param [ Node ] node The node to refresh the peers for. @since 1.0.0
[ "Refresh", "the", "peers", "based", "on", "the", "node", "s", "peers", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/cluster.rb#L376-L383
train
mongoid/moped
lib/moped/cursor.rb
Moped.Cursor.each
def each documents = load_docs documents.each { |doc| yield doc } while more? return kill if limited? && @limit <= 0 documents = get_more documents.each { |doc| yield doc } end end
ruby
def each documents = load_docs documents.each { |doc| yield doc } while more? return kill if limited? && @limit <= 0 documents = get_more documents.each { |doc| yield doc } end end
[ "def", "each", "documents", "=", "load_docs", "documents", ".", "each", "{", "|", "doc", "|", "yield", "doc", "}", "while", "more?", "return", "kill", "if", "limited?", "&&", "@limit", "<=", "0", "documents", "=", "get_more", "documents", ".", "each", "{", "|", "doc", "|", "yield", "doc", "}", "end", "end" ]
Iterate over the results of the query. @example Iterate over the results. cursor.each do |doc| #... end @return [ Enumerator ] The cursor enum. @since 1.0.0
[ "Iterate", "over", "the", "results", "of", "the", "query", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/cursor.rb#L27-L35
train
mongoid/moped
lib/moped/cursor.rb
Moped.Cursor.get_more
def get_more with_retry(session.cluster) do reply = @node.get_more @database, @collection, @cursor_id, request_limit @limit -= reply.count if limited? @cursor_id = reply.cursor_id reply.documents end end
ruby
def get_more with_retry(session.cluster) do reply = @node.get_more @database, @collection, @cursor_id, request_limit @limit -= reply.count if limited? @cursor_id = reply.cursor_id reply.documents end end
[ "def", "get_more", "with_retry", "(", "session", ".", "cluster", ")", "do", "reply", "=", "@node", ".", "get_more", "@database", ",", "@collection", ",", "@cursor_id", ",", "request_limit", "@limit", "-=", "reply", ".", "count", "if", "limited?", "@cursor_id", "=", "reply", ".", "cursor_id", "reply", ".", "documents", "end", "end" ]
Get more documents from the database for the cursor. Executes a get more command. @example Get more docs. cursor.get_more @return [ Array<Hash> ] The next batch of documents. @since 1.0.0
[ "Get", "more", "documents", "from", "the", "database", "for", "the", "cursor", ".", "Executes", "a", "get", "more", "command", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/cursor.rb#L46-L53
train
mongoid/moped
lib/moped/cursor.rb
Moped.Cursor.load_docs
def load_docs @options[:flags] |= [:no_cursor_timeout] if @options[:no_timeout] options = @options.clone options[:limit] = request_limit reply, @node = read_preference.with_node(session.cluster) do |node| [ node.query(@database, @collection, @selector, query_options(options)), node ] end @limit -= reply.count if limited? @cursor_id = reply.cursor_id reply.documents end
ruby
def load_docs @options[:flags] |= [:no_cursor_timeout] if @options[:no_timeout] options = @options.clone options[:limit] = request_limit reply, @node = read_preference.with_node(session.cluster) do |node| [ node.query(@database, @collection, @selector, query_options(options)), node ] end @limit -= reply.count if limited? @cursor_id = reply.cursor_id reply.documents end
[ "def", "load_docs", "@options", "[", ":flags", "]", "|=", "[", ":no_cursor_timeout", "]", "if", "@options", "[", ":no_timeout", "]", "options", "=", "@options", ".", "clone", "options", "[", ":limit", "]", "=", "request_limit", "reply", ",", "@node", "=", "read_preference", ".", "with_node", "(", "session", ".", "cluster", ")", "do", "|", "node", "|", "[", "node", ".", "query", "(", "@database", ",", "@collection", ",", "@selector", ",", "query_options", "(", "options", ")", ")", ",", "node", "]", "end", "@limit", "-=", "reply", ".", "count", "if", "limited?", "@cursor_id", "=", "reply", ".", "cursor_id", "reply", ".", "documents", "end" ]
Load the documents from the database. @example Load the documents. cursor.load_docs @return [ Array<Hash> ] The documents. @since 1.0.0
[ "Load", "the", "documents", "from", "the", "database", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/cursor.rb#L134-L146
train
mongoid/moped
lib/moped/uri.rb
Moped.Uri.options
def options options_string, options = match[10], { database: database } unless options_string.nil? options_string.split(/\&/).each do |option_string| key, value = option_string.split(/=/) if WRITE_OPTIONS.include?(key) options[:write] = { key.to_sym => cast(value) } elsif read = READ_MAPPINGS[value.downcase] options[:read] = read else options[key.to_sym] = cast(value) end end end options end
ruby
def options options_string, options = match[10], { database: database } unless options_string.nil? options_string.split(/\&/).each do |option_string| key, value = option_string.split(/=/) if WRITE_OPTIONS.include?(key) options[:write] = { key.to_sym => cast(value) } elsif read = READ_MAPPINGS[value.downcase] options[:read] = read else options[key.to_sym] = cast(value) end end end options end
[ "def", "options", "options_string", ",", "options", "=", "match", "[", "10", "]", ",", "{", "database", ":", "database", "}", "unless", "options_string", ".", "nil?", "options_string", ".", "split", "(", "/", "\\&", "/", ")", ".", "each", "do", "|", "option_string", "|", "key", ",", "value", "=", "option_string", ".", "split", "(", "/", "/", ")", "if", "WRITE_OPTIONS", ".", "include?", "(", "key", ")", "options", "[", ":write", "]", "=", "{", "key", ".", "to_sym", "=>", "cast", "(", "value", ")", "}", "elsif", "read", "=", "READ_MAPPINGS", "[", "value", ".", "downcase", "]", "options", "[", ":read", "]", "=", "read", "else", "options", "[", "key", ".", "to_sym", "]", "=", "cast", "(", "value", ")", "end", "end", "end", "options", "end" ]
Get the options provided in the URI. @example Get the options uri.options @note The options provided in the URI string must match the MongoDB specification. @return [ Hash ] Options hash usable by Moped @see http://docs.mongodb.org/manual/reference/connection-string/#connections-connection-options @since 1.3.0
[ "Get", "the", "options", "provided", "in", "the", "URI", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/uri.rb#L139-L154
train
mongoid/moped
lib/moped/uri.rb
Moped.Uri.to_hash
def to_hash config = { database: database, hosts: hosts } if username && password config.merge!(username: username, password: password) end config end
ruby
def to_hash config = { database: database, hosts: hosts } if username && password config.merge!(username: username, password: password) end config end
[ "def", "to_hash", "config", "=", "{", "database", ":", "database", ",", "hosts", ":", "hosts", "}", "if", "username", "&&", "password", "config", ".", "merge!", "(", "username", ":", "username", ",", "password", ":", "password", ")", "end", "config", "end" ]
Get the uri as a Mongoid friendly configuration hash. @example Get the uri as a hash. uri.to_hash @return [ Hash ] The uri as options. @since 1.3.0
[ "Get", "the", "uri", "as", "a", "Mongoid", "friendly", "configuration", "hash", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/uri.rb#L176-L182
train
mongoid/moped
lib/moped/database.rb
Moped.Database.command
def command(command) read_preference.with_node(cluster) do |node| node.command(name, command, query_options({})) end end
ruby
def command(command) read_preference.with_node(cluster) do |node| node.command(name, command, query_options({})) end end
[ "def", "command", "(", "command", ")", "read_preference", ".", "with_node", "(", "cluster", ")", "do", "|", "node", "|", "node", ".", "command", "(", "name", ",", "command", ",", "query_options", "(", "{", "}", ")", ")", "end", "end" ]
Run +command+ on the database. @example Run a command. db.command(ismaster: 1) # => { "master" => true, hosts: [] } @param [ Hash ] command The command to run. @return [ Hash ] the result of the command. @since 1.0.0
[ "Run", "+", "command", "+", "on", "the", "database", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/database.rb#L71-L75
train
mongoid/moped
lib/moped/indexes.rb
Moped.Indexes.create
def create(key, options = {}) spec = options.merge(ns: namespace, key: key) spec[:name] ||= key.to_a.join("_") database.session.with(write: { w: 1 }) do |_s| _s[:"system.indexes"].insert(spec) end end
ruby
def create(key, options = {}) spec = options.merge(ns: namespace, key: key) spec[:name] ||= key.to_a.join("_") database.session.with(write: { w: 1 }) do |_s| _s[:"system.indexes"].insert(spec) end end
[ "def", "create", "(", "key", ",", "options", "=", "{", "}", ")", "spec", "=", "options", ".", "merge", "(", "ns", ":", "namespace", ",", "key", ":", "key", ")", "spec", "[", ":name", "]", "||=", "key", ".", "to_a", ".", "join", "(", "\"_\"", ")", "database", ".", "session", ".", "with", "(", "write", ":", "{", "w", ":", "1", "}", ")", "do", "|", "_s", "|", "_s", "[", ":\"", "\"", "]", ".", "insert", "(", "spec", ")", "end", "end" ]
Create an index unless it already exists. @example Without options session[:users].indexes.create(name: 1) session[:users].indexes[name: 1] # => {"v"=>1, "key"=>{"name"=>1}, "ns"=>"moped_test.users", "name"=>"name_1" } @example With options session[:users].indexes.create( { location: "2d", name: 1 }, { unique: true, dropDups: true } ) session[:users][location: "2d", name: 1] {"v"=>1, "key"=>{"location"=>"2d", "name"=>1}, "unique"=>true, "ns"=>"moped_test.users", "dropDups"=>true, "name"=>"location_2d_name_1"} @param [ Hash ] key The index spec. @param [ Hash ] options The options for the index. @return [ Hash ] The index spec. @see http://www.mongodb.org/display/DOCS/Indexes#Indexes-CreationOptions @since 1.0.0
[ "Create", "an", "index", "unless", "it", "already", "exists", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/indexes.rb#L55-L62
train
mongoid/moped
lib/moped/indexes.rb
Moped.Indexes.drop
def drop(key = nil) if key index = self[key] or return false name = index["name"] else name = "*" end result = database.command deleteIndexes: collection_name, index: name result["ok"] == 1 end
ruby
def drop(key = nil) if key index = self[key] or return false name = index["name"] else name = "*" end result = database.command deleteIndexes: collection_name, index: name result["ok"] == 1 end
[ "def", "drop", "(", "key", "=", "nil", ")", "if", "key", "index", "=", "self", "[", "key", "]", "or", "return", "false", "name", "=", "index", "[", "\"name\"", "]", "else", "name", "=", "\"*\"", "end", "result", "=", "database", ".", "command", "deleteIndexes", ":", "collection_name", ",", "index", ":", "name", "result", "[", "\"ok\"", "]", "==", "1", "end" ]
Drop an index, or all indexes. @example Drop all indexes session[:users].indexes.count # => 3 # Does not drop the _id index session[:users].indexes.drop session[:users].indexes.count # => 1 @example Drop a particular index session[:users].indexes.drop(name: 1) session[:users].indexes[name: 1] # => nil @param [ Hash ] key The index's key. @return [ Boolean ] Whether the indexes were dropped. @since 1.0.0
[ "Drop", "an", "index", "or", "all", "indexes", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/indexes.rb#L81-L90
train
mongoid/moped
lib/moped/session.rb
Moped.Session.new
def new(options = {}) session = with(options) session.instance_variable_set(:@cluster, cluster.dup) if block_given? yield(session) else session end end
ruby
def new(options = {}) session = with(options) session.instance_variable_set(:@cluster, cluster.dup) if block_given? yield(session) else session end end
[ "def", "new", "(", "options", "=", "{", "}", ")", "session", "=", "with", "(", "options", ")", "session", ".", "instance_variable_set", "(", ":@cluster", ",", "cluster", ".", "dup", ")", "if", "block_given?", "yield", "(", "session", ")", "else", "session", "end", "end" ]
Initialize a new database session. @example Initialize a new session. Session.new([ "localhost:27017" ]) @param [ Array ] seeds An array of host:port pairs. @param [ Hash ] options The options for the session. @see Above options validations for allowed values in the options hash. @since 1.0.0 Create a new session with +options+ and use new socket connections. @example Change safe mode session.with(write: { w: 2 })[:people].insert(name: "Joe") @example Change safe mode with block session.with(write: { w: 2 }) do |session| session[:people].insert(name: "Joe") end @example Temporarily change database session.with(database: "admin") do |admin| admin.command ismaster: 1 end @example Copy between databases session.use "moped" session.with(database: "backup") do |backup| session[:people].each do |person| backup[:people].insert person end end @param [ Hash ] options The options. @return [ Session ] The new session. @see #with @since 1.0.0 @yieldparam [ Session ] session The new session.
[ "Initialize", "a", "new", "database", "session", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/session.rb#L302-L310
train
mongoid/moped
lib/moped/session.rb
Moped.Session.with
def with(options = {}) session = dup session.options.update(options) if block_given? yield(session) else session end end
ruby
def with(options = {}) session = dup session.options.update(options) if block_given? yield(session) else session end end
[ "def", "with", "(", "options", "=", "{", "}", ")", "session", "=", "dup", "session", ".", "options", ".", "update", "(", "options", ")", "if", "block_given?", "yield", "(", "session", ")", "else", "session", "end", "end" ]
Create a new session with +options+ reusing existing connections. @example Change safe mode session.with(write: { w: 2 })[:people].insert(name: "Joe") @example Change safe mode with block session.with(write: { w: 2 }) do |session| session[:people].insert(name: "Joe") end @example Temporarily change database session.with(database: "admin") do |admin| admin.command ismaster: 1 end @example Copy between databases session.use "moped" session.with(database: "backup") do |backup| session[:people].each do |person| backup[:people].insert person end end @param [ Hash ] options The session options. @return [ Session, Object ] The new session, or the value returned by the block if provided. @since 1.0.0 @yieldparam [ Session ] session The new session.
[ "Create", "a", "new", "session", "with", "+", "options", "+", "reusing", "existing", "connections", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/session.rb#L370-L378
train
mongoid/moped
lib/moped/address.rb
Moped.Address.resolve
def resolve(node) return @resolved if @resolved start = Time.now retries = 0 begin # This timeout should be very large since Timeout::timeout plays very badly with multithreaded code # TODO: Remove this Timeout entirely Timeout::timeout(@timeout * 10) do Resolv.each_address(host) do |ip| if ip =~ Resolv::IPv4::Regex @ip ||= ip break end end raise Resolv::ResolvError unless @ip end @resolved = "#{ip}:#{port}" rescue Timeout::Error, Resolv::ResolvError, SocketError => e msg = [" MOPED:", "Could not resolve IP for: #{original}, delta is #{Time.now - start}, error class is #{e.inspect}, retries is #{retries}. Node is #{node.inspect}", "n/a"] if retries == 0 Loggable.info(*msg) else Loggable.warn(*msg) end if retries < 2 retries += 1 retry else node.down! and false end end end
ruby
def resolve(node) return @resolved if @resolved start = Time.now retries = 0 begin # This timeout should be very large since Timeout::timeout plays very badly with multithreaded code # TODO: Remove this Timeout entirely Timeout::timeout(@timeout * 10) do Resolv.each_address(host) do |ip| if ip =~ Resolv::IPv4::Regex @ip ||= ip break end end raise Resolv::ResolvError unless @ip end @resolved = "#{ip}:#{port}" rescue Timeout::Error, Resolv::ResolvError, SocketError => e msg = [" MOPED:", "Could not resolve IP for: #{original}, delta is #{Time.now - start}, error class is #{e.inspect}, retries is #{retries}. Node is #{node.inspect}", "n/a"] if retries == 0 Loggable.info(*msg) else Loggable.warn(*msg) end if retries < 2 retries += 1 retry else node.down! and false end end end
[ "def", "resolve", "(", "node", ")", "return", "@resolved", "if", "@resolved", "start", "=", "Time", ".", "now", "retries", "=", "0", "begin", "Timeout", "::", "timeout", "(", "@timeout", "*", "10", ")", "do", "Resolv", ".", "each_address", "(", "host", ")", "do", "|", "ip", "|", "if", "ip", "=~", "Resolv", "::", "IPv4", "::", "Regex", "@ip", "||=", "ip", "break", "end", "end", "raise", "Resolv", "::", "ResolvError", "unless", "@ip", "end", "@resolved", "=", "\"#{ip}:#{port}\"", "rescue", "Timeout", "::", "Error", ",", "Resolv", "::", "ResolvError", ",", "SocketError", "=>", "e", "msg", "=", "[", "\" MOPED:\"", ",", "\"Could not resolve IP for: #{original}, delta is #{Time.now - start}, error class is #{e.inspect}, retries is #{retries}. Node is #{node.inspect}\"", ",", "\"n/a\"", "]", "if", "retries", "==", "0", "Loggable", ".", "info", "(", "*", "msg", ")", "else", "Loggable", ".", "warn", "(", "*", "msg", ")", "end", "if", "retries", "<", "2", "retries", "+=", "1", "retry", "else", "node", ".", "down!", "and", "false", "end", "end", "end" ]
Instantiate the new address. @example Instantiate the address. Moped::Address.new("localhost:27017") @param [ String ] address The host:port pair as a string. @since 2.0.0 Resolve the address for the provided node. If the address cannot be resolved the node will be flagged as down. @example Resolve the address. address.resolve(node) @param [ Node ] node The node to resolve for. @return [ String ] The resolved address. @since 2.0.0
[ "Instantiate", "the", "new", "address", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/address.rb#L47-L78
train
mongoid/moped
lib/moped/authenticatable.rb
Moped.Authenticatable.apply_credentials
def apply_credentials(logins) unless credentials == logins logouts = credentials.keys - logins.keys logouts.each do |database| logout(database) end logins.each do |database, (username, password)| unless credentials[database] == [ username, password ] login(database, username, password) end end @original_credentials = credentials.dup end self end
ruby
def apply_credentials(logins) unless credentials == logins logouts = credentials.keys - logins.keys logouts.each do |database| logout(database) end logins.each do |database, (username, password)| unless credentials[database] == [ username, password ] login(database, username, password) end end @original_credentials = credentials.dup end self end
[ "def", "apply_credentials", "(", "logins", ")", "unless", "credentials", "==", "logins", "logouts", "=", "credentials", ".", "keys", "-", "logins", ".", "keys", "logouts", ".", "each", "do", "|", "database", "|", "logout", "(", "database", ")", "end", "logins", ".", "each", "do", "|", "database", ",", "(", "username", ",", "password", ")", "|", "unless", "credentials", "[", "database", "]", "==", "[", "username", ",", "password", "]", "login", "(", "database", ",", "username", ",", "password", ")", "end", "end", "@original_credentials", "=", "credentials", ".", "dup", "end", "self", "end" ]
Apply authentication credentials. @example Apply the authentication credentials. node.apply_credentials({ "moped_test" => [ "user", "pass" ]}) @param [ Hash ] credentials The authentication credentials in the form: { database_name: [ user, password ]} @return [ Object ] The authenticated object. @since 2.0.0
[ "Apply", "authentication", "credentials", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/authenticatable.rb#L20-L34
train
mongoid/moped
lib/moped/authenticatable.rb
Moped.Authenticatable.login
def login(database, username, password) getnonce = Protocol::Command.new(database, getnonce: 1) self.write([getnonce]) reply = self.receive_replies([getnonce]).first if getnonce.failure?(reply) return end result = getnonce.results(reply) authenticate = Protocol::Commands::Authenticate.new(database, username, password, result["nonce"]) self.write([ authenticate ]) document = self.read.documents.first unless result["ok"] == 1 # See if we had connectivity issues so we can retry e = Errors::PotentialReconfiguration.new(authenticate, document) if e.reconfiguring_replica_set? raise Errors::ReplicaSetReconfigured.new(e.command, e.details) elsif e.connection_failure? raise Errors::ConnectionFailure.new(e.inspect) end raise Errors::AuthenticationFailure.new(authenticate, document) end credentials[database] = [username, password] end
ruby
def login(database, username, password) getnonce = Protocol::Command.new(database, getnonce: 1) self.write([getnonce]) reply = self.receive_replies([getnonce]).first if getnonce.failure?(reply) return end result = getnonce.results(reply) authenticate = Protocol::Commands::Authenticate.new(database, username, password, result["nonce"]) self.write([ authenticate ]) document = self.read.documents.first unless result["ok"] == 1 # See if we had connectivity issues so we can retry e = Errors::PotentialReconfiguration.new(authenticate, document) if e.reconfiguring_replica_set? raise Errors::ReplicaSetReconfigured.new(e.command, e.details) elsif e.connection_failure? raise Errors::ConnectionFailure.new(e.inspect) end raise Errors::AuthenticationFailure.new(authenticate, document) end credentials[database] = [username, password] end
[ "def", "login", "(", "database", ",", "username", ",", "password", ")", "getnonce", "=", "Protocol", "::", "Command", ".", "new", "(", "database", ",", "getnonce", ":", "1", ")", "self", ".", "write", "(", "[", "getnonce", "]", ")", "reply", "=", "self", ".", "receive_replies", "(", "[", "getnonce", "]", ")", ".", "first", "if", "getnonce", ".", "failure?", "(", "reply", ")", "return", "end", "result", "=", "getnonce", ".", "results", "(", "reply", ")", "authenticate", "=", "Protocol", "::", "Commands", "::", "Authenticate", ".", "new", "(", "database", ",", "username", ",", "password", ",", "result", "[", "\"nonce\"", "]", ")", "self", ".", "write", "(", "[", "authenticate", "]", ")", "document", "=", "self", ".", "read", ".", "documents", ".", "first", "unless", "result", "[", "\"ok\"", "]", "==", "1", "e", "=", "Errors", "::", "PotentialReconfiguration", ".", "new", "(", "authenticate", ",", "document", ")", "if", "e", ".", "reconfiguring_replica_set?", "raise", "Errors", "::", "ReplicaSetReconfigured", ".", "new", "(", "e", ".", "command", ",", "e", ".", "details", ")", "elsif", "e", ".", "connection_failure?", "raise", "Errors", "::", "ConnectionFailure", ".", "new", "(", "e", ".", "inspect", ")", "end", "raise", "Errors", "::", "AuthenticationFailure", ".", "new", "(", "authenticate", ",", "document", ")", "end", "credentials", "[", "database", "]", "=", "[", "username", ",", "password", "]", "end" ]
Login the user to the provided database with the supplied password. @example Login the user to the database. node.login("moped_test", "user", "pass") @param [ String ] database The database name. @param [ String ] username The username. @param [ String ] password The password. @raise [ Errors::AuthenticationFailure ] If the login failed. @return [ Array ] The username and password. @since 2.0.0
[ "Login", "the", "user", "to", "the", "provided", "database", "with", "the", "supplied", "password", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/authenticatable.rb#L62-L87
train
mongoid/moped
lib/moped/authenticatable.rb
Moped.Authenticatable.logout
def logout(database) command = Protocol::Command.new(database, logout: 1) self.write([command]) reply = self.receive_replies([command]).first if command.failure?(reply) return end credentials.delete(database) end
ruby
def logout(database) command = Protocol::Command.new(database, logout: 1) self.write([command]) reply = self.receive_replies([command]).first if command.failure?(reply) return end credentials.delete(database) end
[ "def", "logout", "(", "database", ")", "command", "=", "Protocol", "::", "Command", ".", "new", "(", "database", ",", "logout", ":", "1", ")", "self", ".", "write", "(", "[", "command", "]", ")", "reply", "=", "self", ".", "receive_replies", "(", "[", "command", "]", ")", ".", "first", "if", "command", ".", "failure?", "(", "reply", ")", "return", "end", "credentials", ".", "delete", "(", "database", ")", "end" ]
Logout the user from the provided database. @example Logout from the provided database. node.logout("moped_test") @param [ String ] database The database name. @return [ Array ] The username and password. @since 2.0.0
[ "Logout", "the", "user", "from", "the", "provided", "database", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/authenticatable.rb#L99-L107
train
mongoid/moped
lib/moped/retryable.rb
Moped.Retryable.with_retry
def with_retry(cluster, retries = cluster.max_retries, &block) begin block.call rescue Errors::ConnectionFailure, Errors::PotentialReconfiguration => e raise e if e.is_a?(Errors::PotentialReconfiguration) && ! (e.message.include?("not master") || e.message.include?("Not primary")) if retries > 0 Loggable.warn(" MOPED:", "Retrying connection attempt #{retries} more time(s), nodes is #{cluster.nodes.inspect}, seeds are #{cluster.seeds.inspect}, cluster is #{cluster.inspect}. Error backtrace is #{e.backtrace}.", "n/a") sleep(cluster.retry_interval) cluster.refresh with_retry(cluster, retries - 1, &block) else raise e end end end
ruby
def with_retry(cluster, retries = cluster.max_retries, &block) begin block.call rescue Errors::ConnectionFailure, Errors::PotentialReconfiguration => e raise e if e.is_a?(Errors::PotentialReconfiguration) && ! (e.message.include?("not master") || e.message.include?("Not primary")) if retries > 0 Loggable.warn(" MOPED:", "Retrying connection attempt #{retries} more time(s), nodes is #{cluster.nodes.inspect}, seeds are #{cluster.seeds.inspect}, cluster is #{cluster.inspect}. Error backtrace is #{e.backtrace}.", "n/a") sleep(cluster.retry_interval) cluster.refresh with_retry(cluster, retries - 1, &block) else raise e end end end
[ "def", "with_retry", "(", "cluster", ",", "retries", "=", "cluster", ".", "max_retries", ",", "&", "block", ")", "begin", "block", ".", "call", "rescue", "Errors", "::", "ConnectionFailure", ",", "Errors", "::", "PotentialReconfiguration", "=>", "e", "raise", "e", "if", "e", ".", "is_a?", "(", "Errors", "::", "PotentialReconfiguration", ")", "&&", "!", "(", "e", ".", "message", ".", "include?", "(", "\"not master\"", ")", "||", "e", ".", "message", ".", "include?", "(", "\"Not primary\"", ")", ")", "if", "retries", ">", "0", "Loggable", ".", "warn", "(", "\" MOPED:\"", ",", "\"Retrying connection attempt #{retries} more time(s), nodes is #{cluster.nodes.inspect}, seeds are #{cluster.seeds.inspect}, cluster is #{cluster.inspect}. Error backtrace is #{e.backtrace}.\"", ",", "\"n/a\"", ")", "sleep", "(", "cluster", ".", "retry_interval", ")", "cluster", ".", "refresh", "with_retry", "(", "cluster", ",", "retries", "-", "1", ",", "&", "block", ")", "else", "raise", "e", "end", "end", "end" ]
Execute the provided block on the cluster and retry if the execution fails. @api private @example Execute with retry. preference.with_retry(cluster) do cluster.with_primary do |node| node.refresh end end @param [ Cluster ] cluster The cluster. @param [ Integer ] retries The number of times to retry. @return [ Object ] The result of the block. @since 2.0.0
[ "Execute", "the", "provided", "block", "on", "the", "cluster", "and", "retry", "if", "the", "execution", "fails", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/retryable.rb#L28-L44
train
mongoid/moped
lib/moped/collection.rb
Moped.Collection.drop
def drop begin session.with(read: :primary).command(drop: name) rescue Moped::Errors::OperationFailure => e raise e unless e.ns_not_found? false end end
ruby
def drop begin session.with(read: :primary).command(drop: name) rescue Moped::Errors::OperationFailure => e raise e unless e.ns_not_found? false end end
[ "def", "drop", "begin", "session", ".", "with", "(", "read", ":", ":primary", ")", ".", "command", "(", "drop", ":", "name", ")", "rescue", "Moped", "::", "Errors", "::", "OperationFailure", "=>", "e", "raise", "e", "unless", "e", ".", "ns_not_found?", "false", "end", "end" ]
Drop the collection. @example Drop the collection. collection.drop @return [ Hash ] The command information. @since 1.0.0
[ "Drop", "the", "collection", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/collection.rb#L40-L47
train
mongoid/moped
lib/moped/collection.rb
Moped.Collection.rename
def rename(to_name) begin session. with(database: "admin", read: :primary). command(renameCollection: "#{database.name}.#{name}", to: "#{database.name}.#{to_name}") rescue Moped::Errors::OperationFailure => e raise e unless e.ns_not_exists? false end end
ruby
def rename(to_name) begin session. with(database: "admin", read: :primary). command(renameCollection: "#{database.name}.#{name}", to: "#{database.name}.#{to_name}") rescue Moped::Errors::OperationFailure => e raise e unless e.ns_not_exists? false end end
[ "def", "rename", "(", "to_name", ")", "begin", "session", ".", "with", "(", "database", ":", "\"admin\"", ",", "read", ":", ":primary", ")", ".", "command", "(", "renameCollection", ":", "\"#{database.name}.#{name}\"", ",", "to", ":", "\"#{database.name}.#{to_name}\"", ")", "rescue", "Moped", "::", "Errors", "::", "OperationFailure", "=>", "e", "raise", "e", "unless", "e", ".", "ns_not_exists?", "false", "end", "end" ]
Rename the collection @example Rename the collection to 'foo' collection.rename('foo') @return [ Hash ] The command information. @since 2.0.0
[ "Rename", "the", "collection" ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/collection.rb#L57-L66
train
mongoid/moped
lib/moped/collection.rb
Moped.Collection.insert
def insert(documents, flags = nil) with_retry(cluster) do docs = documents.is_a?(Array) ? documents : [ documents ] cluster.with_primary do |node| node.insert(database.name, name, docs, write_concern, flags: flags || []) end end end
ruby
def insert(documents, flags = nil) with_retry(cluster) do docs = documents.is_a?(Array) ? documents : [ documents ] cluster.with_primary do |node| node.insert(database.name, name, docs, write_concern, flags: flags || []) end end end
[ "def", "insert", "(", "documents", ",", "flags", "=", "nil", ")", "with_retry", "(", "cluster", ")", "do", "docs", "=", "documents", ".", "is_a?", "(", "Array", ")", "?", "documents", ":", "[", "documents", "]", "cluster", ".", "with_primary", "do", "|", "node", "|", "node", ".", "insert", "(", "database", ".", "name", ",", "name", ",", "docs", ",", "write_concern", ",", "flags", ":", "flags", "||", "[", "]", ")", "end", "end", "end" ]
Initialize the new collection. @example Initialize the collection. Collection.new(database, :artists) @param [ Database ] database The collection's database. @param [ String, Symbol] name The collection name. @since 1.0.0 Insert one or more documents into the collection. @example Insert a single document. db[:people].insert(name: "John") @example Insert multiple documents in batch. db[:people].insert([{name: "John"}, {name: "Joe"}]) @param [ Hash, Array<Hash> ] documents The document(s) to insert. @param [ Array ] flags The flags, valid values are :continue_on_error. @option options [Array] :continue_on_error Whether to continue on error. @return [ nil ] nil. @since 1.0.0
[ "Initialize", "the", "new", "collection", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/collection.rb#L124-L131
train
mongoid/moped
lib/moped/query.rb
Moped.Query.count
def count(limit = false) command = { count: collection.name, query: selector } command.merge!(skip: operation.skip, limit: operation.limit) if limit result = collection.database.command(command) result["n"].to_i end
ruby
def count(limit = false) command = { count: collection.name, query: selector } command.merge!(skip: operation.skip, limit: operation.limit) if limit result = collection.database.command(command) result["n"].to_i end
[ "def", "count", "(", "limit", "=", "false", ")", "command", "=", "{", "count", ":", "collection", ".", "name", ",", "query", ":", "selector", "}", "command", ".", "merge!", "(", "skip", ":", "operation", ".", "skip", ",", "limit", ":", "operation", ".", "limit", ")", "if", "limit", "result", "=", "collection", ".", "database", ".", "command", "(", "command", ")", "result", "[", "\"n\"", "]", ".", "to_i", "end" ]
Get the count of matching documents in the query. @example Get the count. db[:people].find.count @return [ Integer ] The number of documents that match the selector. @since 1.0.0
[ "Get", "the", "count", "of", "matching", "documents", "in", "the", "query", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/query.rb#L39-L44
train
mongoid/moped
lib/moped/query.rb
Moped.Query.distinct
def distinct(key) result = collection.database.command( distinct: collection.name, key: key.to_s, query: selector ) result["values"] end
ruby
def distinct(key) result = collection.database.command( distinct: collection.name, key: key.to_s, query: selector ) result["values"] end
[ "def", "distinct", "(", "key", ")", "result", "=", "collection", ".", "database", ".", "command", "(", "distinct", ":", "collection", ".", "name", ",", "key", ":", "key", ".", "to_s", ",", "query", ":", "selector", ")", "result", "[", "\"values\"", "]", "end" ]
Get the distinct values in the collection for the provided key. @example Get the distinct values. db[:people].find.distinct(:name) @param [ Symbol, String ] key The name of the field. @return [ Array<Object ] The distinct values. @since 1.0.0
[ "Get", "the", "distinct", "values", "in", "the", "collection", "for", "the", "provided", "key", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/query.rb#L56-L63
train
mongoid/moped
lib/moped/query.rb
Moped.Query.explain
def explain explanation = operation.selector.dup hint = explanation["$hint"] sort = explanation["$orderby"] max_scan = explanation["$maxScan"] explanation = { "$query" => selector, "$explain" => true, } explanation["$orderby"] = sort if sort explanation["$hint"] = hint if hint explanation["$maxScan"] = max_scan if max_scan Query.new(collection, explanation).limit(-(operation.limit.abs)).each { |doc| return doc } end
ruby
def explain explanation = operation.selector.dup hint = explanation["$hint"] sort = explanation["$orderby"] max_scan = explanation["$maxScan"] explanation = { "$query" => selector, "$explain" => true, } explanation["$orderby"] = sort if sort explanation["$hint"] = hint if hint explanation["$maxScan"] = max_scan if max_scan Query.new(collection, explanation).limit(-(operation.limit.abs)).each { |doc| return doc } end
[ "def", "explain", "explanation", "=", "operation", ".", "selector", ".", "dup", "hint", "=", "explanation", "[", "\"$hint\"", "]", "sort", "=", "explanation", "[", "\"$orderby\"", "]", "max_scan", "=", "explanation", "[", "\"$maxScan\"", "]", "explanation", "=", "{", "\"$query\"", "=>", "selector", ",", "\"$explain\"", "=>", "true", ",", "}", "explanation", "[", "\"$orderby\"", "]", "=", "sort", "if", "sort", "explanation", "[", "\"$hint\"", "]", "=", "hint", "if", "hint", "explanation", "[", "\"$maxScan\"", "]", "=", "max_scan", "if", "max_scan", "Query", ".", "new", "(", "collection", ",", "explanation", ")", ".", "limit", "(", "-", "(", "operation", ".", "limit", ".", "abs", ")", ")", ".", "each", "{", "|", "doc", "|", "return", "doc", "}", "end" ]
Explain the current query. @example Explain the query. db[:people].find.explain @return [ Hash ] The explain document. @since 1.0.0
[ "Explain", "the", "current", "query", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/query.rb#L104-L117
train
mongoid/moped
lib/moped/query.rb
Moped.Query.first
def first reply = read_preference.with_node(cluster) do |node| node.query( operation.database, operation.collection, operation.selector, query_options( fields: operation.fields, flags: operation.flags, skip: operation.skip, limit: -1 ) ) end reply.documents.first end
ruby
def first reply = read_preference.with_node(cluster) do |node| node.query( operation.database, operation.collection, operation.selector, query_options( fields: operation.fields, flags: operation.flags, skip: operation.skip, limit: -1 ) ) end reply.documents.first end
[ "def", "first", "reply", "=", "read_preference", ".", "with_node", "(", "cluster", ")", "do", "|", "node", "|", "node", ".", "query", "(", "operation", ".", "database", ",", "operation", ".", "collection", ",", "operation", ".", "selector", ",", "query_options", "(", "fields", ":", "operation", ".", "fields", ",", "flags", ":", "operation", ".", "flags", ",", "skip", ":", "operation", ".", "skip", ",", "limit", ":", "-", "1", ")", ")", "end", "reply", ".", "documents", ".", "first", "end" ]
Get the first matching document. @example Get the first matching document. db[:people].find.first @return [ Hash ] The first document that matches the selector. @since 1.0.0
[ "Get", "the", "first", "matching", "document", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/query.rb#L127-L142
train
mongoid/moped
lib/moped/query.rb
Moped.Query.remove
def remove with_retry(cluster) do cluster.with_primary do |node| node.remove( operation.database, operation.collection, operation.basic_selector, write_concern, flags: [ :remove_first ] ) end end end
ruby
def remove with_retry(cluster) do cluster.with_primary do |node| node.remove( operation.database, operation.collection, operation.basic_selector, write_concern, flags: [ :remove_first ] ) end end end
[ "def", "remove", "with_retry", "(", "cluster", ")", "do", "cluster", ".", "with_primary", "do", "|", "node", "|", "node", ".", "remove", "(", "operation", ".", "database", ",", "operation", ".", "collection", ",", "operation", ".", "basic_selector", ",", "write_concern", ",", "flags", ":", "[", ":remove_first", "]", ")", "end", "end", "end" ]
Remove a single document matching the query's selector. @example Remove a single document. db[:people].find(name: "John").remove @return [ Hash, nil ] If in safe mode the last error result. @since 1.0.0
[ "Remove", "a", "single", "document", "matching", "the", "query", "s", "selector", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/query.rb#L324-L336
train
mongoid/moped
lib/moped/query.rb
Moped.Query.update
def update(change, flags = nil) with_retry(cluster) do cluster.with_primary do |node| node.update( operation.database, operation.collection, operation.selector["$query"] || operation.selector, change, write_concern, flags: flags ) end end end
ruby
def update(change, flags = nil) with_retry(cluster) do cluster.with_primary do |node| node.update( operation.database, operation.collection, operation.selector["$query"] || operation.selector, change, write_concern, flags: flags ) end end end
[ "def", "update", "(", "change", ",", "flags", "=", "nil", ")", "with_retry", "(", "cluster", ")", "do", "cluster", ".", "with_primary", "do", "|", "node", "|", "node", ".", "update", "(", "operation", ".", "database", ",", "operation", ".", "collection", ",", "operation", ".", "selector", "[", "\"$query\"", "]", "||", "operation", ".", "selector", ",", "change", ",", "write_concern", ",", "flags", ":", "flags", ")", "end", "end", "end" ]
Update a single document matching the query's selector. @example Update the first matching document. db[:people].find(_id: 1).update(name: "John") @param [ Hash ] change The changes to make to the document @param [ Array ] flags An array of operation flags. Valid values are: +:multi+ and +:upsert+ @return [ Hash, nil ] If in safe mode the last error result. @since 1.0.0
[ "Update", "a", "single", "document", "matching", "the", "query", "s", "selector", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/query.rb#L430-L443
train
mongoid/moped
lib/moped/write_concern.rb
Moped.WriteConcern.get
def get(value) propagate = value[:w] || value["w"] if propagate == 0 || propagate == -1 Unverified.new else Propagate.new(value) end end
ruby
def get(value) propagate = value[:w] || value["w"] if propagate == 0 || propagate == -1 Unverified.new else Propagate.new(value) end end
[ "def", "get", "(", "value", ")", "propagate", "=", "value", "[", ":w", "]", "||", "value", "[", "\"w\"", "]", "if", "propagate", "==", "0", "||", "propagate", "==", "-", "1", "Unverified", ".", "new", "else", "Propagate", ".", "new", "(", "value", ")", "end", "end" ]
Get the corresponding write concern for the provided value. If the value is unverified we get that concern, otherwise we get propagate. @example Get the appropriate write concern. Moped::WriteConcern.get(w: 3) @param [ Symbol, String, Hash ] The value to use to get the concern. @return [ Unverified, Propagate ] The appropriate write concern. @since 2.0.0
[ "Get", "the", "corresponding", "write", "concern", "for", "the", "provided", "value", ".", "If", "the", "value", "is", "unverified", "we", "get", "that", "concern", "otherwise", "we", "get", "propagate", "." ]
cf817ca58a85ed567c2711e4eada163018bde3cf
https://github.com/mongoid/moped/blob/cf817ca58a85ed567c2711e4eada163018bde3cf/lib/moped/write_concern.rb#L24-L31
train
cheezy/ADB
lib/ADB/instrumentation.rb
ADB.Instrumentation.instrument
def instrument(runner, args = {}) with(the(args) << using_the(runner)) raise ADBError, last_stdout unless last_stdout.empty? end
ruby
def instrument(runner, args = {}) with(the(args) << using_the(runner)) raise ADBError, last_stdout unless last_stdout.empty? end
[ "def", "instrument", "(", "runner", ",", "args", "=", "{", "}", ")", "with", "(", "the", "(", "args", ")", "<<", "using_the", "(", "runner", ")", ")", "raise", "ADBError", ",", "last_stdout", "unless", "last_stdout", ".", "empty?", "end" ]
send instrumentation requests @example instrument "com.example/android.test.InstrumentationTestRunner" # will run all of the tests within the 'com.example' package using the 'android.test.InstrumentationTestRunner' @example instrument "com.example/android.test.InstrumentationTestRunner", :class => "com.example.test.SomeTestClass" # will execute all of the tests within 'com.example.test.SomeTestClass' @param [String] runner indicates the package/runner to instrument @param [Hash] collection of key/value pairs to be sent as arguments to the instrumentation runner
[ "send", "instrumentation", "requests" ]
fa0dece75bc15b5cec68d4c7e9a24115bbb1a3e7
https://github.com/cheezy/ADB/blob/fa0dece75bc15b5cec68d4c7e9a24115bbb1a3e7/lib/ADB/instrumentation.rb#L20-L23
train
wvanbergen/scoped_search
lib/scoped_search/query_builder.rb
ScopedSearch.QueryBuilder.build_find_params
def build_find_params(options) keyconditions = [] keyparameters = [] parameters = [] includes = [] joins = [] # Build SQL WHERE clause using the AST sql = @ast.to_sql(self, definition) do |notification, value| # Handle the notifications encountered during the SQL generation: # Store the parameters, includes, etc so that they can be added to # the find-hash later on. case notification when :keycondition then keyconditions << value when :keyparameter then keyparameters << value when :parameter then parameters << value when :include then includes << value when :joins then joins << value else raise ScopedSearch::QueryNotSupported, "Cannot handle #{notification.inspect}: #{value.inspect}" end end # Build SQL ORDER BY clause order = order_by(options[:order]) do |notification, value| case notification when :parameter then parameters << value when :include then includes << value when :joins then joins << value else raise ScopedSearch::QueryNotSupported, "Cannot handle #{notification.inspect}: #{value.inspect}" end end sql = (keyconditions + (sql.blank? ? [] : [sql]) ).map {|c| "(#{c})"}.join(" AND ") # Build hash for ActiveRecord::Base#find for the named scope find_attributes = {} find_attributes[:conditions] = [sql] + keyparameters + parameters unless sql.blank? find_attributes[:include] = includes.uniq unless includes.empty? find_attributes[:joins] = joins.uniq unless joins.empty? find_attributes[:order] = order unless order.nil? # p find_attributes # Uncomment for debugging return find_attributes end
ruby
def build_find_params(options) keyconditions = [] keyparameters = [] parameters = [] includes = [] joins = [] # Build SQL WHERE clause using the AST sql = @ast.to_sql(self, definition) do |notification, value| # Handle the notifications encountered during the SQL generation: # Store the parameters, includes, etc so that they can be added to # the find-hash later on. case notification when :keycondition then keyconditions << value when :keyparameter then keyparameters << value when :parameter then parameters << value when :include then includes << value when :joins then joins << value else raise ScopedSearch::QueryNotSupported, "Cannot handle #{notification.inspect}: #{value.inspect}" end end # Build SQL ORDER BY clause order = order_by(options[:order]) do |notification, value| case notification when :parameter then parameters << value when :include then includes << value when :joins then joins << value else raise ScopedSearch::QueryNotSupported, "Cannot handle #{notification.inspect}: #{value.inspect}" end end sql = (keyconditions + (sql.blank? ? [] : [sql]) ).map {|c| "(#{c})"}.join(" AND ") # Build hash for ActiveRecord::Base#find for the named scope find_attributes = {} find_attributes[:conditions] = [sql] + keyparameters + parameters unless sql.blank? find_attributes[:include] = includes.uniq unless includes.empty? find_attributes[:joins] = joins.uniq unless joins.empty? find_attributes[:order] = order unless order.nil? # p find_attributes # Uncomment for debugging return find_attributes end
[ "def", "build_find_params", "(", "options", ")", "keyconditions", "=", "[", "]", "keyparameters", "=", "[", "]", "parameters", "=", "[", "]", "includes", "=", "[", "]", "joins", "=", "[", "]", "sql", "=", "@ast", ".", "to_sql", "(", "self", ",", "definition", ")", "do", "|", "notification", ",", "value", "|", "case", "notification", "when", ":keycondition", "then", "keyconditions", "<<", "value", "when", ":keyparameter", "then", "keyparameters", "<<", "value", "when", ":parameter", "then", "parameters", "<<", "value", "when", ":include", "then", "includes", "<<", "value", "when", ":joins", "then", "joins", "<<", "value", "else", "raise", "ScopedSearch", "::", "QueryNotSupported", ",", "\"Cannot handle #{notification.inspect}: #{value.inspect}\"", "end", "end", "order", "=", "order_by", "(", "options", "[", ":order", "]", ")", "do", "|", "notification", ",", "value", "|", "case", "notification", "when", ":parameter", "then", "parameters", "<<", "value", "when", ":include", "then", "includes", "<<", "value", "when", ":joins", "then", "joins", "<<", "value", "else", "raise", "ScopedSearch", "::", "QueryNotSupported", ",", "\"Cannot handle #{notification.inspect}: #{value.inspect}\"", "end", "end", "sql", "=", "(", "keyconditions", "+", "(", "sql", ".", "blank?", "?", "[", "]", ":", "[", "sql", "]", ")", ")", ".", "map", "{", "|", "c", "|", "\"(#{c})\"", "}", ".", "join", "(", "\" AND \"", ")", "find_attributes", "=", "{", "}", "find_attributes", "[", ":conditions", "]", "=", "[", "sql", "]", "+", "keyparameters", "+", "parameters", "unless", "sql", ".", "blank?", "find_attributes", "[", ":include", "]", "=", "includes", ".", "uniq", "unless", "includes", ".", "empty?", "find_attributes", "[", ":joins", "]", "=", "joins", ".", "uniq", "unless", "joins", ".", "empty?", "find_attributes", "[", ":order", "]", "=", "order", "unless", "order", ".", "nil?", "return", "find_attributes", "end" ]
Initializes the instance by setting the relevant parameters Actually builds the find parameters hash that should be used in the search_for named scope.
[ "Initializes", "the", "instance", "by", "setting", "the", "relevant", "parameters", "Actually", "builds", "the", "find", "parameters", "hash", "that", "should", "be", "used", "in", "the", "search_for", "named", "scope", "." ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/query_builder.rb#L46-L87
train
wvanbergen/scoped_search
lib/scoped_search/query_builder.rb
ScopedSearch.QueryBuilder.sql_operator
def sql_operator(operator, field) raise ScopedSearch::QueryNotSupported, "the operator '#{operator}' is not supported for field type '#{field.type}'" if !field.virtual? and [:like, :unlike].include?(operator) and !field.textual? SQL_OPERATORS[operator] end
ruby
def sql_operator(operator, field) raise ScopedSearch::QueryNotSupported, "the operator '#{operator}' is not supported for field type '#{field.type}'" if !field.virtual? and [:like, :unlike].include?(operator) and !field.textual? SQL_OPERATORS[operator] end
[ "def", "sql_operator", "(", "operator", ",", "field", ")", "raise", "ScopedSearch", "::", "QueryNotSupported", ",", "\"the operator '#{operator}' is not supported for field type '#{field.type}'\"", "if", "!", "field", ".", "virtual?", "and", "[", ":like", ",", ":unlike", "]", ".", "include?", "(", "operator", ")", "and", "!", "field", ".", "textual?", "SQL_OPERATORS", "[", "operator", "]", "end" ]
Return the SQL operator to use given an operator symbol and field definition. By default, it will simply look up the correct SQL operator in the SQL_OPERATORS hash, but this can be overridden by a database adapter.
[ "Return", "the", "SQL", "operator", "to", "use", "given", "an", "operator", "symbol", "and", "field", "definition", "." ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/query_builder.rb#L115-L118
train
wvanbergen/scoped_search
lib/scoped_search/query_builder.rb
ScopedSearch.QueryBuilder.translate_value
def translate_value(field, value) translated_value = field.complete_value[value.to_sym] raise ScopedSearch::QueryNotSupported, "'#{field.field}' should be one of '#{field.complete_value.keys.join(', ')}', but the query was '#{value}'" if translated_value.nil? translated_value end
ruby
def translate_value(field, value) translated_value = field.complete_value[value.to_sym] raise ScopedSearch::QueryNotSupported, "'#{field.field}' should be one of '#{field.complete_value.keys.join(', ')}', but the query was '#{value}'" if translated_value.nil? translated_value end
[ "def", "translate_value", "(", "field", ",", "value", ")", "translated_value", "=", "field", ".", "complete_value", "[", "value", ".", "to_sym", "]", "raise", "ScopedSearch", "::", "QueryNotSupported", ",", "\"'#{field.field}' should be one of '#{field.complete_value.keys.join(', ')}', but the query was '#{value}'\"", "if", "translated_value", ".", "nil?", "translated_value", "end" ]
Validate the key name is in the set and translate the value to the set value.
[ "Validate", "the", "key", "name", "is", "in", "the", "set", "and", "translate", "the", "value", "to", "the", "set", "value", "." ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/query_builder.rb#L178-L182
train
wvanbergen/scoped_search
lib/scoped_search/rails_helper.rb
ScopedSearch.RailsHelper.sort
def sort(field, as: nil, default: "ASC", html_options: {}, url_options: params) unless as id = field.to_s.downcase == "id" as = id ? field.to_s.upcase : field.to_s.humanize end ascend = "#{field} ASC" descend = "#{field} DESC" selected_sort = [ascend, descend].find { |o| o == params[:order] } case params[:order] when ascend new_sort = descend when descend new_sort = ascend else new_sort = ["ASC", "DESC"].include?(default) ? "#{field} #{default}" : ascend end unless selected_sort.nil? css_classes = html_options[:class] ? html_options[:class].split(" ") : [] if selected_sort == ascend as = "&#9650;&nbsp;".html_safe + as css_classes << "ascending" else as = "&#9660;&nbsp;".html_safe + as css_classes << "descending" end html_options[:class] = css_classes.join(" ") end url_options = url_options.to_h if url_options.respond_to?(:permit) # convert ActionController::Parameters if given url_options = url_options.merge(:order => new_sort) as = raw(as) if defined?(RailsXss) content_tag(:a, as, html_options.merge(href: url_for(url_options))) end
ruby
def sort(field, as: nil, default: "ASC", html_options: {}, url_options: params) unless as id = field.to_s.downcase == "id" as = id ? field.to_s.upcase : field.to_s.humanize end ascend = "#{field} ASC" descend = "#{field} DESC" selected_sort = [ascend, descend].find { |o| o == params[:order] } case params[:order] when ascend new_sort = descend when descend new_sort = ascend else new_sort = ["ASC", "DESC"].include?(default) ? "#{field} #{default}" : ascend end unless selected_sort.nil? css_classes = html_options[:class] ? html_options[:class].split(" ") : [] if selected_sort == ascend as = "&#9650;&nbsp;".html_safe + as css_classes << "ascending" else as = "&#9660;&nbsp;".html_safe + as css_classes << "descending" end html_options[:class] = css_classes.join(" ") end url_options = url_options.to_h if url_options.respond_to?(:permit) # convert ActionController::Parameters if given url_options = url_options.merge(:order => new_sort) as = raw(as) if defined?(RailsXss) content_tag(:a, as, html_options.merge(href: url_for(url_options))) end
[ "def", "sort", "(", "field", ",", "as", ":", "nil", ",", "default", ":", "\"ASC\"", ",", "html_options", ":", "{", "}", ",", "url_options", ":", "params", ")", "unless", "as", "id", "=", "field", ".", "to_s", ".", "downcase", "==", "\"id\"", "as", "=", "id", "?", "field", ".", "to_s", ".", "upcase", ":", "field", ".", "to_s", ".", "humanize", "end", "ascend", "=", "\"#{field} ASC\"", "descend", "=", "\"#{field} DESC\"", "selected_sort", "=", "[", "ascend", ",", "descend", "]", ".", "find", "{", "|", "o", "|", "o", "==", "params", "[", ":order", "]", "}", "case", "params", "[", ":order", "]", "when", "ascend", "new_sort", "=", "descend", "when", "descend", "new_sort", "=", "ascend", "else", "new_sort", "=", "[", "\"ASC\"", ",", "\"DESC\"", "]", ".", "include?", "(", "default", ")", "?", "\"#{field} #{default}\"", ":", "ascend", "end", "unless", "selected_sort", ".", "nil?", "css_classes", "=", "html_options", "[", ":class", "]", "?", "html_options", "[", ":class", "]", ".", "split", "(", "\" \"", ")", ":", "[", "]", "if", "selected_sort", "==", "ascend", "as", "=", "\"&#9650;&nbsp;\"", ".", "html_safe", "+", "as", "css_classes", "<<", "\"ascending\"", "else", "as", "=", "\"&#9660;&nbsp;\"", ".", "html_safe", "+", "as", "css_classes", "<<", "\"descending\"", "end", "html_options", "[", ":class", "]", "=", "css_classes", ".", "join", "(", "\" \"", ")", "end", "url_options", "=", "url_options", ".", "to_h", "if", "url_options", ".", "respond_to?", "(", ":permit", ")", "url_options", "=", "url_options", ".", "merge", "(", ":order", "=>", "new_sort", ")", "as", "=", "raw", "(", "as", ")", "if", "defined?", "(", "RailsXss", ")", "content_tag", "(", ":a", ",", "as", ",", "html_options", ".", "merge", "(", "href", ":", "url_for", "(", "url_options", ")", ")", ")", "end" ]
Creates a link that alternates between ascending and descending. Examples: sort :username sort :created_at, as: "Created" sort :created_at, default: "DESC" * <tt>field</tt> - the name of the named scope. This helper will prepend this value with "ascend_by_" and "descend_by_" This helper accepts the following options: * <tt>:as</tt> - the text used in the link, defaults to whatever is passed to `field` * <tt>:default</tt> - default sorting order, DESC or ASC * <tt>:html_options</tt> - is a hash of HTML options for the anchor tag * <tt>:url_options</tt> - is a hash of URL parameters, defaulting to `params`, to preserve the current URL parameters. On Rails 5 or higher, parameter whitelisting prevents any parameter being used in a link by default, so `params.permit(..)` should be passed for `url_options` for all known and permitted URL parameters, e.g. sort :username, url_options: params.permit(:search)
[ "Creates", "a", "link", "that", "alternates", "between", "ascending", "and", "descending", "." ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/rails_helper.rb#L27-L65
train
wvanbergen/scoped_search
lib/scoped_search/auto_complete_builder.rb
ScopedSearch.AutoCompleteBuilder.build_autocomplete_options
def build_autocomplete_options # First parse to find illegal syntax in the existing query, # this method will throw exception on bad syntax. is_query_valid # get the completion options node = last_node completion = complete_options(node) suggestions = [] suggestions += complete_keyword if completion.include?(:keyword) suggestions += LOGICAL_INFIX_OPERATORS if completion.include?(:logical_op) suggestions += LOGICAL_PREFIX_OPERATORS + NULL_PREFIX_COMPLETER if completion.include?(:prefix_op) suggestions += complete_operator(node) if completion.include?(:infix_op) suggestions += complete_value if completion.include?(:value) build_suggestions(suggestions, completion.include?(:value)) end
ruby
def build_autocomplete_options # First parse to find illegal syntax in the existing query, # this method will throw exception on bad syntax. is_query_valid # get the completion options node = last_node completion = complete_options(node) suggestions = [] suggestions += complete_keyword if completion.include?(:keyword) suggestions += LOGICAL_INFIX_OPERATORS if completion.include?(:logical_op) suggestions += LOGICAL_PREFIX_OPERATORS + NULL_PREFIX_COMPLETER if completion.include?(:prefix_op) suggestions += complete_operator(node) if completion.include?(:infix_op) suggestions += complete_value if completion.include?(:value) build_suggestions(suggestions, completion.include?(:value)) end
[ "def", "build_autocomplete_options", "is_query_valid", "node", "=", "last_node", "completion", "=", "complete_options", "(", "node", ")", "suggestions", "=", "[", "]", "suggestions", "+=", "complete_keyword", "if", "completion", ".", "include?", "(", ":keyword", ")", "suggestions", "+=", "LOGICAL_INFIX_OPERATORS", "if", "completion", ".", "include?", "(", ":logical_op", ")", "suggestions", "+=", "LOGICAL_PREFIX_OPERATORS", "+", "NULL_PREFIX_COMPLETER", "if", "completion", ".", "include?", "(", ":prefix_op", ")", "suggestions", "+=", "complete_operator", "(", "node", ")", "if", "completion", ".", "include?", "(", ":infix_op", ")", "suggestions", "+=", "complete_value", "if", "completion", ".", "include?", "(", ":value", ")", "build_suggestions", "(", "suggestions", ",", "completion", ".", "include?", "(", ":value", ")", ")", "end" ]
Initializes the instance by setting the relevant parameters Test the validity of the current query and suggest possible completion
[ "Initializes", "the", "instance", "by", "setting", "the", "relevant", "parameters", "Test", "the", "validity", "of", "the", "current", "query", "and", "suggest", "possible", "completion" ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/auto_complete_builder.rb#L34-L51
train
wvanbergen/scoped_search
lib/scoped_search/auto_complete_builder.rb
ScopedSearch.AutoCompleteBuilder.complete_options
def complete_options(node) return [:keyword] + [:prefix_op] if tokens.empty? #prefix operator return [:keyword] if last_token_is(PREFIX_OPERATORS) # left hand if is_left_hand(node) if (tokens.size == 1 || last_token_is(PREFIX_OPERATORS + LOGICAL_INFIX_OPERATORS) || last_token_is(PREFIX_OPERATORS + LOGICAL_INFIX_OPERATORS, 2)) options = [:keyword] options += [:prefix_op] unless last_token_is(PREFIX_OPERATORS) else options = [:logical_op] end return options end if is_right_hand # right hand return [:value] else # comparison operator completer return [:infix_op] end end
ruby
def complete_options(node) return [:keyword] + [:prefix_op] if tokens.empty? #prefix operator return [:keyword] if last_token_is(PREFIX_OPERATORS) # left hand if is_left_hand(node) if (tokens.size == 1 || last_token_is(PREFIX_OPERATORS + LOGICAL_INFIX_OPERATORS) || last_token_is(PREFIX_OPERATORS + LOGICAL_INFIX_OPERATORS, 2)) options = [:keyword] options += [:prefix_op] unless last_token_is(PREFIX_OPERATORS) else options = [:logical_op] end return options end if is_right_hand # right hand return [:value] else # comparison operator completer return [:infix_op] end end
[ "def", "complete_options", "(", "node", ")", "return", "[", ":keyword", "]", "+", "[", ":prefix_op", "]", "if", "tokens", ".", "empty?", "return", "[", ":keyword", "]", "if", "last_token_is", "(", "PREFIX_OPERATORS", ")", "if", "is_left_hand", "(", "node", ")", "if", "(", "tokens", ".", "size", "==", "1", "||", "last_token_is", "(", "PREFIX_OPERATORS", "+", "LOGICAL_INFIX_OPERATORS", ")", "||", "last_token_is", "(", "PREFIX_OPERATORS", "+", "LOGICAL_INFIX_OPERATORS", ",", "2", ")", ")", "options", "=", "[", ":keyword", "]", "options", "+=", "[", ":prefix_op", "]", "unless", "last_token_is", "(", "PREFIX_OPERATORS", ")", "else", "options", "=", "[", ":logical_op", "]", "end", "return", "options", "end", "if", "is_right_hand", "return", "[", ":value", "]", "else", "return", "[", ":infix_op", "]", "end", "end" ]
parse the query and return the complete options
[ "parse", "the", "query", "and", "return", "the", "complete", "options" ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/auto_complete_builder.rb#L54-L80
train
wvanbergen/scoped_search
lib/scoped_search/auto_complete_builder.rb
ScopedSearch.AutoCompleteBuilder.complete_keyword
def complete_keyword keywords = [] definition.fields.each do|f| next unless f[1].complete_enabled if (f[1].key_field) keywords += complete_key(f[0], f[1], tokens.last) else keywords << f[0].to_s + ' ' end end keywords.sort end
ruby
def complete_keyword keywords = [] definition.fields.each do|f| next unless f[1].complete_enabled if (f[1].key_field) keywords += complete_key(f[0], f[1], tokens.last) else keywords << f[0].to_s + ' ' end end keywords.sort end
[ "def", "complete_keyword", "keywords", "=", "[", "]", "definition", ".", "fields", ".", "each", "do", "|", "f", "|", "next", "unless", "f", "[", "1", "]", ".", "complete_enabled", "if", "(", "f", "[", "1", "]", ".", "key_field", ")", "keywords", "+=", "complete_key", "(", "f", "[", "0", "]", ",", "f", "[", "1", "]", ",", "tokens", ".", "last", ")", "else", "keywords", "<<", "f", "[", "0", "]", ".", "to_s", "+", "' '", "end", "end", "keywords", ".", "sort", "end" ]
suggest all searchable field names. in relations suggest only the long format relation.field.
[ "suggest", "all", "searchable", "field", "names", ".", "in", "relations", "suggest", "only", "the", "long", "format", "relation", ".", "field", "." ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/auto_complete_builder.rb#L154-L165
train
wvanbergen/scoped_search
lib/scoped_search/auto_complete_builder.rb
ScopedSearch.AutoCompleteBuilder.complete_key
def complete_key(name, field, val) return ["#{name}."] if !val || !val.is_a?(String) || !(val.include?('.')) val = val.sub(/.*\./,'') connection = definition.klass.connection quoted_table = field.key_klass.connection.quote_table_name(field.key_klass.table_name) quoted_field = field.key_klass.connection.quote_column_name(field.key_field) field_name = "#{quoted_table}.#{quoted_field}" field.key_klass .where(value_conditions(field_name, val)) .select(field_name) .limit(20) .distinct .map(&field.key_field) .compact .map { |f| "#{name}.#{f} " } end
ruby
def complete_key(name, field, val) return ["#{name}."] if !val || !val.is_a?(String) || !(val.include?('.')) val = val.sub(/.*\./,'') connection = definition.klass.connection quoted_table = field.key_klass.connection.quote_table_name(field.key_klass.table_name) quoted_field = field.key_klass.connection.quote_column_name(field.key_field) field_name = "#{quoted_table}.#{quoted_field}" field.key_klass .where(value_conditions(field_name, val)) .select(field_name) .limit(20) .distinct .map(&field.key_field) .compact .map { |f| "#{name}.#{f} " } end
[ "def", "complete_key", "(", "name", ",", "field", ",", "val", ")", "return", "[", "\"#{name}.\"", "]", "if", "!", "val", "||", "!", "val", ".", "is_a?", "(", "String", ")", "||", "!", "(", "val", ".", "include?", "(", "'.'", ")", ")", "val", "=", "val", ".", "sub", "(", "/", "\\.", "/", ",", "''", ")", "connection", "=", "definition", ".", "klass", ".", "connection", "quoted_table", "=", "field", ".", "key_klass", ".", "connection", ".", "quote_table_name", "(", "field", ".", "key_klass", ".", "table_name", ")", "quoted_field", "=", "field", ".", "key_klass", ".", "connection", ".", "quote_column_name", "(", "field", ".", "key_field", ")", "field_name", "=", "\"#{quoted_table}.#{quoted_field}\"", "field", ".", "key_klass", ".", "where", "(", "value_conditions", "(", "field_name", ",", "val", ")", ")", ".", "select", "(", "field_name", ")", ".", "limit", "(", "20", ")", ".", "distinct", ".", "map", "(", "&", "field", ".", "key_field", ")", ".", "compact", ".", "map", "{", "|", "f", "|", "\"#{name}.#{f} \"", "}", "end" ]
this method completes the keys list in a key-value schema in the format table.keyName
[ "this", "method", "completes", "the", "keys", "list", "in", "a", "key", "-", "value", "schema", "in", "the", "format", "table", ".", "keyName" ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/auto_complete_builder.rb#L168-L185
train
wvanbergen/scoped_search
lib/scoped_search/auto_complete_builder.rb
ScopedSearch.AutoCompleteBuilder.complete_date_value
def complete_date_value options = [] options << '"30 minutes ago"' options << '"1 hour ago"' options << '"2 hours ago"' options << 'Today' options << 'Yesterday' options << 'Tomorrow' options << 2.days.ago.strftime('%A') options << 3.days.ago.strftime('%A') options << 4.days.ago.strftime('%A') options << 5.days.ago.strftime('%A') options << '"6 days ago"' options << 7.days.ago.strftime('"%b %d,%Y"') options << '"2 weeks from now"' options end
ruby
def complete_date_value options = [] options << '"30 minutes ago"' options << '"1 hour ago"' options << '"2 hours ago"' options << 'Today' options << 'Yesterday' options << 'Tomorrow' options << 2.days.ago.strftime('%A') options << 3.days.ago.strftime('%A') options << 4.days.ago.strftime('%A') options << 5.days.ago.strftime('%A') options << '"6 days ago"' options << 7.days.ago.strftime('"%b %d,%Y"') options << '"2 weeks from now"' options end
[ "def", "complete_date_value", "options", "=", "[", "]", "options", "<<", "'\"30 minutes ago\"'", "options", "<<", "'\"1 hour ago\"'", "options", "<<", "'\"2 hours ago\"'", "options", "<<", "'Today'", "options", "<<", "'Yesterday'", "options", "<<", "'Tomorrow'", "options", "<<", "2", ".", "days", ".", "ago", ".", "strftime", "(", "'%A'", ")", "options", "<<", "3", ".", "days", ".", "ago", ".", "strftime", "(", "'%A'", ")", "options", "<<", "4", ".", "days", ".", "ago", ".", "strftime", "(", "'%A'", ")", "options", "<<", "5", ".", "days", ".", "ago", ".", "strftime", "(", "'%A'", ")", "options", "<<", "'\"6 days ago\"'", "options", "<<", "7", ".", "days", ".", "ago", ".", "strftime", "(", "'\"%b %d,%Y\"'", ")", "options", "<<", "'\"2 weeks from now\"'", "options", "end" ]
date value completer
[ "date", "value", "completer" ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/auto_complete_builder.rb#L231-L247
train
wvanbergen/scoped_search
lib/scoped_search/auto_complete_builder.rb
ScopedSearch.AutoCompleteBuilder.complete_key_value
def complete_key_value(field, token, val) key_name = token.sub(/^.*\./,"") key_klass = field.key_klass.where(field.key_field => key_name).first raise ScopedSearch::QueryNotSupported, "Field '#{key_name}' not recognized for searching!" if key_klass.nil? query = completer_scope(field) if field.key_klass != field.klass key = field.key_klass.to_s.gsub(/.*::/,'').underscore.to_sym fk = definition.reflection_by_name(field.klass, key).association_foreign_key.to_sym query = query.where(fk => key_klass.id) end query .where(value_conditions(field.quoted_field, val)) .select("DISTINCT #{field.quoted_field}") .limit(20) .map(&field.field) .compact .map { |v| v.to_s =~ /\s/ ? "\"#{v}\"" : v } end
ruby
def complete_key_value(field, token, val) key_name = token.sub(/^.*\./,"") key_klass = field.key_klass.where(field.key_field => key_name).first raise ScopedSearch::QueryNotSupported, "Field '#{key_name}' not recognized for searching!" if key_klass.nil? query = completer_scope(field) if field.key_klass != field.klass key = field.key_klass.to_s.gsub(/.*::/,'').underscore.to_sym fk = definition.reflection_by_name(field.klass, key).association_foreign_key.to_sym query = query.where(fk => key_klass.id) end query .where(value_conditions(field.quoted_field, val)) .select("DISTINCT #{field.quoted_field}") .limit(20) .map(&field.field) .compact .map { |v| v.to_s =~ /\s/ ? "\"#{v}\"" : v } end
[ "def", "complete_key_value", "(", "field", ",", "token", ",", "val", ")", "key_name", "=", "token", ".", "sub", "(", "/", "\\.", "/", ",", "\"\"", ")", "key_klass", "=", "field", ".", "key_klass", ".", "where", "(", "field", ".", "key_field", "=>", "key_name", ")", ".", "first", "raise", "ScopedSearch", "::", "QueryNotSupported", ",", "\"Field '#{key_name}' not recognized for searching!\"", "if", "key_klass", ".", "nil?", "query", "=", "completer_scope", "(", "field", ")", "if", "field", ".", "key_klass", "!=", "field", ".", "klass", "key", "=", "field", ".", "key_klass", ".", "to_s", ".", "gsub", "(", "/", "/", ",", "''", ")", ".", "underscore", ".", "to_sym", "fk", "=", "definition", ".", "reflection_by_name", "(", "field", ".", "klass", ",", "key", ")", ".", "association_foreign_key", ".", "to_sym", "query", "=", "query", ".", "where", "(", "fk", "=>", "key_klass", ".", "id", ")", "end", "query", ".", "where", "(", "value_conditions", "(", "field", ".", "quoted_field", ",", "val", ")", ")", ".", "select", "(", "\"DISTINCT #{field.quoted_field}\"", ")", ".", "limit", "(", "20", ")", ".", "map", "(", "&", "field", ".", "field", ")", ".", "compact", ".", "map", "{", "|", "v", "|", "v", ".", "to_s", "=~", "/", "\\s", "/", "?", "\"\\\"#{v}\\\"\"", ":", "v", "}", "end" ]
complete values in a key-value schema
[ "complete", "values", "in", "a", "key", "-", "value", "schema" ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/auto_complete_builder.rb#L250-L270
train
wvanbergen/scoped_search
lib/scoped_search/auto_complete_builder.rb
ScopedSearch.AutoCompleteBuilder.complete_operator
def complete_operator(node) definition.operator_by_field_name(node.value).map { |o| o.end_with?(' ') ? o : "#{o} " } end
ruby
def complete_operator(node) definition.operator_by_field_name(node.value).map { |o| o.end_with?(' ') ? o : "#{o} " } end
[ "def", "complete_operator", "(", "node", ")", "definition", ".", "operator_by_field_name", "(", "node", ".", "value", ")", ".", "map", "{", "|", "o", "|", "o", ".", "end_with?", "(", "' '", ")", "?", "o", ":", "\"#{o} \"", "}", "end" ]
This method complete infix operators by field type
[ "This", "method", "complete", "infix", "operators", "by", "field", "type" ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/auto_complete_builder.rb#L278-L280
train
wvanbergen/scoped_search
lib/scoped_search.rb
ScopedSearch.ClassMethods.scoped_search
def scoped_search(*definitions) self.scoped_search_definition ||= ScopedSearch::Definition.new(self) unless self.scoped_search_definition.klass == self # inheriting the parent self.scoped_search_definition = ScopedSearch::Definition.new(self) end definitions.each do |definition| if definition[:on].kind_of?(Array) definition[:on].each { |field| self.scoped_search_definition.define(definition.merge(:on => field)) } else self.scoped_search_definition.define(definition) end end return self.scoped_search_definition end
ruby
def scoped_search(*definitions) self.scoped_search_definition ||= ScopedSearch::Definition.new(self) unless self.scoped_search_definition.klass == self # inheriting the parent self.scoped_search_definition = ScopedSearch::Definition.new(self) end definitions.each do |definition| if definition[:on].kind_of?(Array) definition[:on].each { |field| self.scoped_search_definition.define(definition.merge(:on => field)) } else self.scoped_search_definition.define(definition) end end return self.scoped_search_definition end
[ "def", "scoped_search", "(", "*", "definitions", ")", "self", ".", "scoped_search_definition", "||=", "ScopedSearch", "::", "Definition", ".", "new", "(", "self", ")", "unless", "self", ".", "scoped_search_definition", ".", "klass", "==", "self", "self", ".", "scoped_search_definition", "=", "ScopedSearch", "::", "Definition", ".", "new", "(", "self", ")", "end", "definitions", ".", "each", "do", "|", "definition", "|", "if", "definition", "[", ":on", "]", ".", "kind_of?", "(", "Array", ")", "definition", "[", ":on", "]", ".", "each", "{", "|", "field", "|", "self", ".", "scoped_search_definition", ".", "define", "(", "definition", ".", "merge", "(", ":on", "=>", "field", ")", ")", "}", "else", "self", ".", "scoped_search_definition", ".", "define", "(", "definition", ")", "end", "end", "return", "self", ".", "scoped_search_definition", "end" ]
Export the scoped_search method fo defining the search options. This method will create a definition instance for the class if it does not yet exist, or if a parent definition exists then it will create a new one inheriting it, and use the object as block argument and return value.
[ "Export", "the", "scoped_search", "method", "fo", "defining", "the", "search", "options", ".", "This", "method", "will", "create", "a", "definition", "instance", "for", "the", "class", "if", "it", "does", "not", "yet", "exist", "or", "if", "a", "parent", "definition", "exists", "then", "it", "will", "create", "a", "new", "one", "inheriting", "it", "and", "use", "the", "object", "as", "block", "argument", "and", "return", "value", "." ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search.rb#L29-L43
train
wvanbergen/scoped_search
lib/scoped_search/definition.rb
ScopedSearch.Definition.operator_by_field_name
def operator_by_field_name(name) field = field_by_name(name) return [] if field.nil? return field.operators if field.operators return ['=', '!=', '>', '<', '<=', '>=', '~', '!~', '^', '!^'] if field.virtual? return ['=', '!='] if field.set? || field.uuid? return ['=', '>', '<', '<=', '>=', '!=', '^', '!^'] if field.numerical? return ['=', '!=', '~', '!~', '^', '!^'] if field.textual? return ['=', '>', '<'] if field.temporal? raise ScopedSearch::QueryNotSupported, "Unsupported type '#{field.type.inspect}')' for field '#{name}'. This can be a result of a search definition problem." end
ruby
def operator_by_field_name(name) field = field_by_name(name) return [] if field.nil? return field.operators if field.operators return ['=', '!=', '>', '<', '<=', '>=', '~', '!~', '^', '!^'] if field.virtual? return ['=', '!='] if field.set? || field.uuid? return ['=', '>', '<', '<=', '>=', '!=', '^', '!^'] if field.numerical? return ['=', '!=', '~', '!~', '^', '!^'] if field.textual? return ['=', '>', '<'] if field.temporal? raise ScopedSearch::QueryNotSupported, "Unsupported type '#{field.type.inspect}')' for field '#{name}'. This can be a result of a search definition problem." end
[ "def", "operator_by_field_name", "(", "name", ")", "field", "=", "field_by_name", "(", "name", ")", "return", "[", "]", "if", "field", ".", "nil?", "return", "field", ".", "operators", "if", "field", ".", "operators", "return", "[", "'='", ",", "'!='", ",", "'>'", ",", "'<'", ",", "'<='", ",", "'>='", ",", "'~'", ",", "'!~'", ",", "'^'", ",", "'!^'", "]", "if", "field", ".", "virtual?", "return", "[", "'='", ",", "'!='", "]", "if", "field", ".", "set?", "||", "field", ".", "uuid?", "return", "[", "'='", ",", "'>'", ",", "'<'", ",", "'<='", ",", "'>='", ",", "'!='", ",", "'^'", ",", "'!^'", "]", "if", "field", ".", "numerical?", "return", "[", "'='", ",", "'!='", ",", "'~'", ",", "'!~'", ",", "'^'", ",", "'!^'", "]", "if", "field", ".", "textual?", "return", "[", "'='", ",", "'>'", ",", "'<'", "]", "if", "field", ".", "temporal?", "raise", "ScopedSearch", "::", "QueryNotSupported", ",", "\"Unsupported type '#{field.type.inspect}')' for field '#{name}'. This can be a result of a search definition problem.\"", "end" ]
this method is used by the syntax auto completer to suggest operators.
[ "this", "method", "is", "used", "by", "the", "syntax", "auto", "completer", "to", "suggest", "operators", "." ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/definition.rb#L249-L259
train
wvanbergen/scoped_search
lib/scoped_search/definition.rb
ScopedSearch.Definition.default_fields_for
def default_fields_for(value, operator = nil) column_types = [:virtual] column_types += [:string, :text] if [nil, :like, :unlike, :ne, :eq].include?(operator) column_types += [:double, :float, :decimal] if value =~ NUMERICAL_REGXP column_types += [:integer] if value =~ INTEGER_REGXP column_types += [:uuid] if value =~ UUID_REGXP column_types += [:datetime, :date, :timestamp] if (parse_temporal(value)) default_fields.select { |field| !field.set? && column_types.include?(field.type) } end
ruby
def default_fields_for(value, operator = nil) column_types = [:virtual] column_types += [:string, :text] if [nil, :like, :unlike, :ne, :eq].include?(operator) column_types += [:double, :float, :decimal] if value =~ NUMERICAL_REGXP column_types += [:integer] if value =~ INTEGER_REGXP column_types += [:uuid] if value =~ UUID_REGXP column_types += [:datetime, :date, :timestamp] if (parse_temporal(value)) default_fields.select { |field| !field.set? && column_types.include?(field.type) } end
[ "def", "default_fields_for", "(", "value", ",", "operator", "=", "nil", ")", "column_types", "=", "[", ":virtual", "]", "column_types", "+=", "[", ":string", ",", ":text", "]", "if", "[", "nil", ",", ":like", ",", ":unlike", ",", ":ne", ",", ":eq", "]", ".", "include?", "(", "operator", ")", "column_types", "+=", "[", ":double", ",", ":float", ",", ":decimal", "]", "if", "value", "=~", "NUMERICAL_REGXP", "column_types", "+=", "[", ":integer", "]", "if", "value", "=~", "INTEGER_REGXP", "column_types", "+=", "[", ":uuid", "]", "if", "value", "=~", "UUID_REGXP", "column_types", "+=", "[", ":datetime", ",", ":date", ",", ":timestamp", "]", "if", "(", "parse_temporal", "(", "value", ")", ")", "default_fields", ".", "select", "{", "|", "field", "|", "!", "field", ".", "set?", "&&", "column_types", ".", "include?", "(", "field", ".", "type", ")", "}", "end" ]
Returns a list of appropriate fields to search in given a search keyword and operator.
[ "Returns", "a", "list", "of", "appropriate", "fields", "to", "search", "in", "given", "a", "search", "keyword", "and", "operator", "." ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/definition.rb#L266-L276
train
wvanbergen/scoped_search
lib/scoped_search/definition.rb
ScopedSearch.Definition.parse_temporal
def parse_temporal(value) return Date.current if value =~ /\btoday\b/i return 1.day.ago.to_date if value =~ /\byesterday\b/i return 1.day.from_now.to_date if value =~ /\btomorrow\b/i return (eval($1.strip.gsub(/\s+/,'.').downcase)).to_datetime if value =~ /\A\s*(\d+\s+\b(?:hours?|minutes?)\b\s+\bago)\b\s*\z/i return (eval($1.strip.gsub(/\s+/,'.').downcase)).to_date if value =~ /\A\s*(\d+\s+\b(?:days?|weeks?|months?|years?)\b\s+\bago)\b\s*\z/i return (eval($1.strip.gsub(/from\s+now/i,'from_now').gsub(/\s+/,'.').downcase)).to_datetime if value =~ /\A\s*(\d+\s+\b(?:hours?|minutes?)\b\s+\bfrom\s+now)\b\s*\z/i return (eval($1.strip.gsub(/from\s+now/i,'from_now').gsub(/\s+/,'.').downcase)).to_date if value =~ /\A\s*(\d+\s+\b(?:days?|weeks?|months?|years?)\b\s+\bfrom\s+now)\b\s*\z/i DateTime.parse(value, true) rescue nil end
ruby
def parse_temporal(value) return Date.current if value =~ /\btoday\b/i return 1.day.ago.to_date if value =~ /\byesterday\b/i return 1.day.from_now.to_date if value =~ /\btomorrow\b/i return (eval($1.strip.gsub(/\s+/,'.').downcase)).to_datetime if value =~ /\A\s*(\d+\s+\b(?:hours?|minutes?)\b\s+\bago)\b\s*\z/i return (eval($1.strip.gsub(/\s+/,'.').downcase)).to_date if value =~ /\A\s*(\d+\s+\b(?:days?|weeks?|months?|years?)\b\s+\bago)\b\s*\z/i return (eval($1.strip.gsub(/from\s+now/i,'from_now').gsub(/\s+/,'.').downcase)).to_datetime if value =~ /\A\s*(\d+\s+\b(?:hours?|minutes?)\b\s+\bfrom\s+now)\b\s*\z/i return (eval($1.strip.gsub(/from\s+now/i,'from_now').gsub(/\s+/,'.').downcase)).to_date if value =~ /\A\s*(\d+\s+\b(?:days?|weeks?|months?|years?)\b\s+\bfrom\s+now)\b\s*\z/i DateTime.parse(value, true) rescue nil end
[ "def", "parse_temporal", "(", "value", ")", "return", "Date", ".", "current", "if", "value", "=~", "/", "\\b", "\\b", "/i", "return", "1", ".", "day", ".", "ago", ".", "to_date", "if", "value", "=~", "/", "\\b", "\\b", "/i", "return", "1", ".", "day", ".", "from_now", ".", "to_date", "if", "value", "=~", "/", "\\b", "\\b", "/i", "return", "(", "eval", "(", "$1", ".", "strip", ".", "gsub", "(", "/", "\\s", "/", ",", "'.'", ")", ".", "downcase", ")", ")", ".", "to_datetime", "if", "value", "=~", "/", "\\A", "\\s", "\\d", "\\s", "\\b", "\\b", "\\s", "\\b", "\\b", "\\s", "\\z", "/i", "return", "(", "eval", "(", "$1", ".", "strip", ".", "gsub", "(", "/", "\\s", "/", ",", "'.'", ")", ".", "downcase", ")", ")", ".", "to_date", "if", "value", "=~", "/", "\\A", "\\s", "\\d", "\\s", "\\b", "\\b", "\\s", "\\b", "\\b", "\\s", "\\z", "/i", "return", "(", "eval", "(", "$1", ".", "strip", ".", "gsub", "(", "/", "\\s", "/i", ",", "'from_now'", ")", ".", "gsub", "(", "/", "\\s", "/", ",", "'.'", ")", ".", "downcase", ")", ")", ".", "to_datetime", "if", "value", "=~", "/", "\\A", "\\s", "\\d", "\\s", "\\b", "\\b", "\\s", "\\b", "\\s", "\\b", "\\s", "\\z", "/i", "return", "(", "eval", "(", "$1", ".", "strip", ".", "gsub", "(", "/", "\\s", "/i", ",", "'from_now'", ")", ".", "gsub", "(", "/", "\\s", "/", ",", "'.'", ")", ".", "downcase", ")", ")", ".", "to_date", "if", "value", "=~", "/", "\\A", "\\s", "\\d", "\\s", "\\b", "\\b", "\\s", "\\b", "\\s", "\\b", "\\s", "\\z", "/i", "DateTime", ".", "parse", "(", "value", ",", "true", ")", "rescue", "nil", "end" ]
Try to parse a string as a datetime. Supported formats are Today, Yesterday, Sunday, '1 day ago', '2 hours ago', '3 months ago', '4 weeks from now', 'Jan 23, 2004' And many more formats that are documented in Ruby DateTime API Doc.
[ "Try", "to", "parse", "a", "string", "as", "a", "datetime", ".", "Supported", "formats", "are", "Today", "Yesterday", "Sunday", "1", "day", "ago", "2", "hours", "ago", "3", "months", "ago", "4", "weeks", "from", "now", "Jan", "23", "2004", "And", "many", "more", "formats", "that", "are", "documented", "in", "Ruby", "DateTime", "API", "Doc", "." ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/definition.rb#L281-L290
train
wvanbergen/scoped_search
lib/scoped_search/definition.rb
ScopedSearch.Definition.reflection_by_name
def reflection_by_name(klass, name) return if name.nil? klass.reflections[name.to_sym] || klass.reflections[name.to_s] end
ruby
def reflection_by_name(klass, name) return if name.nil? klass.reflections[name.to_sym] || klass.reflections[name.to_s] end
[ "def", "reflection_by_name", "(", "klass", ",", "name", ")", "return", "if", "name", ".", "nil?", "klass", ".", "reflections", "[", "name", ".", "to_sym", "]", "||", "klass", ".", "reflections", "[", "name", ".", "to_s", "]", "end" ]
Returns a reflection for a given klass and name
[ "Returns", "a", "reflection", "for", "a", "given", "klass", "and", "name" ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/definition.rb#L306-L309
train
wvanbergen/scoped_search
lib/scoped_search/definition.rb
ScopedSearch.Definition.register_named_scope!
def register_named_scope! # :nodoc @klass.define_singleton_method(:search_for) do |query = '', options = {}| # klass may be different to @klass if the scope is called on a subclass klass = self definition = klass.scoped_search_definition search_scope = klass.all find_options = ScopedSearch::QueryBuilder.build_query(definition, query || '', options) search_scope = search_scope.where(find_options[:conditions]) if find_options[:conditions] search_scope = search_scope.includes(find_options[:include]) if find_options[:include] search_scope = search_scope.joins(find_options[:joins]) if find_options[:joins] search_scope = search_scope.reorder(find_options[:order]) if find_options[:order] search_scope = search_scope.references(find_options[:include]) if find_options[:include] search_scope end end
ruby
def register_named_scope! # :nodoc @klass.define_singleton_method(:search_for) do |query = '', options = {}| # klass may be different to @klass if the scope is called on a subclass klass = self definition = klass.scoped_search_definition search_scope = klass.all find_options = ScopedSearch::QueryBuilder.build_query(definition, query || '', options) search_scope = search_scope.where(find_options[:conditions]) if find_options[:conditions] search_scope = search_scope.includes(find_options[:include]) if find_options[:include] search_scope = search_scope.joins(find_options[:joins]) if find_options[:joins] search_scope = search_scope.reorder(find_options[:order]) if find_options[:order] search_scope = search_scope.references(find_options[:include]) if find_options[:include] search_scope end end
[ "def", "register_named_scope!", "@klass", ".", "define_singleton_method", "(", ":search_for", ")", "do", "|", "query", "=", "''", ",", "options", "=", "{", "}", "|", "klass", "=", "self", "definition", "=", "klass", ".", "scoped_search_definition", "search_scope", "=", "klass", ".", "all", "find_options", "=", "ScopedSearch", "::", "QueryBuilder", ".", "build_query", "(", "definition", ",", "query", "||", "''", ",", "options", ")", "search_scope", "=", "search_scope", ".", "where", "(", "find_options", "[", ":conditions", "]", ")", "if", "find_options", "[", ":conditions", "]", "search_scope", "=", "search_scope", ".", "includes", "(", "find_options", "[", ":include", "]", ")", "if", "find_options", "[", ":include", "]", "search_scope", "=", "search_scope", ".", "joins", "(", "find_options", "[", ":joins", "]", ")", "if", "find_options", "[", ":joins", "]", "search_scope", "=", "search_scope", ".", "reorder", "(", "find_options", "[", ":order", "]", ")", "if", "find_options", "[", ":order", "]", "search_scope", "=", "search_scope", ".", "references", "(", "find_options", "[", ":include", "]", ")", "if", "find_options", "[", ":include", "]", "search_scope", "end", "end" ]
Registers the search_for named scope within the class that is used for searching.
[ "Registers", "the", "search_for", "named", "scope", "within", "the", "class", "that", "is", "used", "for", "searching", "." ]
b56f7c41965c46cce4dc8b153cfdca8cb806d25d
https://github.com/wvanbergen/scoped_search/blob/b56f7c41965c46cce4dc8b153cfdca8cb806d25d/lib/scoped_search/definition.rb#L314-L330
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.method_missing
def method_missing(name, *args) # Queries if @collections.include?(name.to_s) @query = build_collection_query_object(name,@additional_params, *args) return @query # Adds elsif name.to_s =~ /^AddTo(.*)/ type = $1 if @collections.include?(type) @save_operations << Operation.new("Add", $1, args[0]) else super end elsif @function_imports.include?(name.to_s) execute_import_function(name.to_s, args) else super end end
ruby
def method_missing(name, *args) # Queries if @collections.include?(name.to_s) @query = build_collection_query_object(name,@additional_params, *args) return @query # Adds elsif name.to_s =~ /^AddTo(.*)/ type = $1 if @collections.include?(type) @save_operations << Operation.new("Add", $1, args[0]) else super end elsif @function_imports.include?(name.to_s) execute_import_function(name.to_s, args) else super end end
[ "def", "method_missing", "(", "name", ",", "*", "args", ")", "if", "@collections", ".", "include?", "(", "name", ".", "to_s", ")", "@query", "=", "build_collection_query_object", "(", "name", ",", "@additional_params", ",", "*", "args", ")", "return", "@query", "elsif", "name", ".", "to_s", "=~", "/", "/", "type", "=", "$1", "if", "@collections", ".", "include?", "(", "type", ")", "@save_operations", "<<", "Operation", ".", "new", "(", "\"Add\"", ",", "$1", ",", "args", "[", "0", "]", ")", "else", "super", "end", "elsif", "@function_imports", ".", "include?", "(", "name", ".", "to_s", ")", "execute_import_function", "(", "name", ".", "to_s", ",", "args", ")", "else", "super", "end", "end" ]
Creates a new instance of the Service class @param [String] service_uri the root URI of the OData service @param [Hash] options the options to pass to the service @option options [String] :username for http basic auth @option options [String] :password for http basic auth @option options [Object] :verify_ssl false if no verification, otherwise mode (OpenSSL::SSL::VERIFY_PEER is default) @option options [Hash] :rest_options a hash of rest-client options that will be passed to all OData::Resource.new calls @option options [Hash] :additional_params a hash of query string params that will be passed on all calls @option options [Boolean, true] :eager_partial true if queries should consume partial feeds until the feed is complete, false if explicit calls to next must be performed Handles the dynamic `AddTo<EntityName>` methods as well as the collections on the service
[ "Creates", "a", "new", "instance", "of", "the", "Service", "class" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L24-L42
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.delete_object
def delete_object(obj) type = obj.class.to_s if obj.respond_to?(:__metadata) && !obj.send(:__metadata).nil? @save_operations << Operation.new("Delete", type, obj) else raise OData::NotSupportedError.new "You cannot delete a non-tracked entity" end end
ruby
def delete_object(obj) type = obj.class.to_s if obj.respond_to?(:__metadata) && !obj.send(:__metadata).nil? @save_operations << Operation.new("Delete", type, obj) else raise OData::NotSupportedError.new "You cannot delete a non-tracked entity" end end
[ "def", "delete_object", "(", "obj", ")", "type", "=", "obj", ".", "class", ".", "to_s", "if", "obj", ".", "respond_to?", "(", ":__metadata", ")", "&&", "!", "obj", ".", "send", "(", ":__metadata", ")", ".", "nil?", "@save_operations", "<<", "Operation", ".", "new", "(", "\"Delete\"", ",", "type", ",", "obj", ")", "else", "raise", "OData", "::", "NotSupportedError", ".", "new", "\"You cannot delete a non-tracked entity\"", "end", "end" ]
Queues an object for deletion. To actually remove it from the server, you must call save_changes as well. @param [Object] obj the object to mark for deletion @raise [NotSupportedError] if the `obj` isn't a tracked entity
[ "Queues", "an", "object", "for", "deletion", ".", "To", "actually", "remove", "it", "from", "the", "server", "you", "must", "call", "save_changes", "as", "well", "." ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L49-L56
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.respond_to?
def respond_to?(method) if @collections.include?(method.to_s) return true # Adds elsif method.to_s =~ /^AddTo(.*)/ type = $1 if @collections.include?(type) return true else super end # Function Imports elsif @function_imports.include?(method.to_s) return true else super end end
ruby
def respond_to?(method) if @collections.include?(method.to_s) return true # Adds elsif method.to_s =~ /^AddTo(.*)/ type = $1 if @collections.include?(type) return true else super end # Function Imports elsif @function_imports.include?(method.to_s) return true else super end end
[ "def", "respond_to?", "(", "method", ")", "if", "@collections", ".", "include?", "(", "method", ".", "to_s", ")", "return", "true", "elsif", "method", ".", "to_s", "=~", "/", "/", "type", "=", "$1", "if", "@collections", ".", "include?", "(", "type", ")", "return", "true", "else", "super", "end", "elsif", "@function_imports", ".", "include?", "(", "method", ".", "to_s", ")", "return", "true", "else", "super", "end", "end" ]
Overridden to identify methods handled by method_missing
[ "Overridden", "to", "identify", "methods", "handled", "by", "method_missing" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L109-L126
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.load_property
def load_property(obj, nav_prop) raise NotSupportedError, "You cannot load a property on an entity that isn't tracked" if obj.send(:__metadata).nil? raise ArgumentError, "'#{nav_prop}' is not a valid navigation property" unless obj.respond_to?(nav_prop.to_sym) raise ArgumentError, "'#{nav_prop}' is not a valid navigation property" unless @class_metadata[obj.class.to_s][nav_prop].nav_prop results = OData::Resource.new(build_load_property_uri(obj, nav_prop), @rest_options).get prop_results = build_classes_from_result(results.body) obj.send "#{nav_prop}=", (singular?(nav_prop) ? prop_results.first : prop_results) end
ruby
def load_property(obj, nav_prop) raise NotSupportedError, "You cannot load a property on an entity that isn't tracked" if obj.send(:__metadata).nil? raise ArgumentError, "'#{nav_prop}' is not a valid navigation property" unless obj.respond_to?(nav_prop.to_sym) raise ArgumentError, "'#{nav_prop}' is not a valid navigation property" unless @class_metadata[obj.class.to_s][nav_prop].nav_prop results = OData::Resource.new(build_load_property_uri(obj, nav_prop), @rest_options).get prop_results = build_classes_from_result(results.body) obj.send "#{nav_prop}=", (singular?(nav_prop) ? prop_results.first : prop_results) end
[ "def", "load_property", "(", "obj", ",", "nav_prop", ")", "raise", "NotSupportedError", ",", "\"You cannot load a property on an entity that isn't tracked\"", "if", "obj", ".", "send", "(", ":__metadata", ")", ".", "nil?", "raise", "ArgumentError", ",", "\"'#{nav_prop}' is not a valid navigation property\"", "unless", "obj", ".", "respond_to?", "(", "nav_prop", ".", "to_sym", ")", "raise", "ArgumentError", ",", "\"'#{nav_prop}' is not a valid navigation property\"", "unless", "@class_metadata", "[", "obj", ".", "class", ".", "to_s", "]", "[", "nav_prop", "]", ".", "nav_prop", "results", "=", "OData", "::", "Resource", ".", "new", "(", "build_load_property_uri", "(", "obj", ",", "nav_prop", ")", ",", "@rest_options", ")", ".", "get", "prop_results", "=", "build_classes_from_result", "(", "results", ".", "body", ")", "obj", ".", "send", "\"#{nav_prop}=\"", ",", "(", "singular?", "(", "nav_prop", ")", "?", "prop_results", ".", "first", ":", "prop_results", ")", "end" ]
Lazy loads a navigation property on a model @param [Object] obj the object to fill @param [String] nav_prop the navigation property to fill @raise [NotSupportedError] if the `obj` isn't a tracked entity @raise [ArgumentError] if the `nav_prop` isn't a valid navigation property
[ "Lazy", "loads", "a", "navigation", "property", "on", "a", "model" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L146-L153
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.add_link
def add_link(parent, nav_prop, child) raise NotSupportedError, "You cannot add a link on an entity that isn't tracked (#{parent.class})" if parent.send(:__metadata).nil? raise ArgumentError, "'#{nav_prop}' is not a valid navigation property for #{parent.class}" unless parent.respond_to?(nav_prop.to_sym) raise ArgumentError, "'#{nav_prop}' is not a valid navigation property for #{parent.class}" unless @class_metadata[parent.class.to_s][nav_prop].nav_prop raise NotSupportedError, "You cannot add a link on a child entity that isn't tracked (#{child.class})" if child.send(:__metadata).nil? @save_operations << Operation.new("AddLink", nav_prop, parent, child) end
ruby
def add_link(parent, nav_prop, child) raise NotSupportedError, "You cannot add a link on an entity that isn't tracked (#{parent.class})" if parent.send(:__metadata).nil? raise ArgumentError, "'#{nav_prop}' is not a valid navigation property for #{parent.class}" unless parent.respond_to?(nav_prop.to_sym) raise ArgumentError, "'#{nav_prop}' is not a valid navigation property for #{parent.class}" unless @class_metadata[parent.class.to_s][nav_prop].nav_prop raise NotSupportedError, "You cannot add a link on a child entity that isn't tracked (#{child.class})" if child.send(:__metadata).nil? @save_operations << Operation.new("AddLink", nav_prop, parent, child) end
[ "def", "add_link", "(", "parent", ",", "nav_prop", ",", "child", ")", "raise", "NotSupportedError", ",", "\"You cannot add a link on an entity that isn't tracked (#{parent.class})\"", "if", "parent", ".", "send", "(", ":__metadata", ")", ".", "nil?", "raise", "ArgumentError", ",", "\"'#{nav_prop}' is not a valid navigation property for #{parent.class}\"", "unless", "parent", ".", "respond_to?", "(", "nav_prop", ".", "to_sym", ")", "raise", "ArgumentError", ",", "\"'#{nav_prop}' is not a valid navigation property for #{parent.class}\"", "unless", "@class_metadata", "[", "parent", ".", "class", ".", "to_s", "]", "[", "nav_prop", "]", ".", "nav_prop", "raise", "NotSupportedError", ",", "\"You cannot add a link on a child entity that isn't tracked (#{child.class})\"", "if", "child", ".", "send", "(", ":__metadata", ")", ".", "nil?", "@save_operations", "<<", "Operation", ".", "new", "(", "\"AddLink\"", ",", "nav_prop", ",", "parent", ",", "child", ")", "end" ]
Adds a child object to a parent object's collection @param [Object] parent the parent object @param [String] nav_prop the name of the navigation property to add the child to @param [Object] child the child object @raise [NotSupportedError] if the `parent` isn't a tracked entity @raise [ArgumentError] if the `nav_prop` isn't a valid navigation property @raise [NotSupportedError] if the `child` isn't a tracked entity
[ "Adds", "a", "child", "object", "to", "a", "parent", "object", "s", "collection" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L163-L169
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.build_collection_query_object
def build_collection_query_object(name, additional_parameters, *args) root = "/#{name.to_s}" if args.empty? #nothing to add elsif args.size == 1 if args.first.to_s =~ /\d+/ id_metadata = find_id_metadata(name.to_s) root << build_id_path(args.first, id_metadata) else root << "(#{args.first})" end else root << "(#{args.join(',')})" end QueryBuilder.new(root, additional_parameters) end
ruby
def build_collection_query_object(name, additional_parameters, *args) root = "/#{name.to_s}" if args.empty? #nothing to add elsif args.size == 1 if args.first.to_s =~ /\d+/ id_metadata = find_id_metadata(name.to_s) root << build_id_path(args.first, id_metadata) else root << "(#{args.first})" end else root << "(#{args.join(',')})" end QueryBuilder.new(root, additional_parameters) end
[ "def", "build_collection_query_object", "(", "name", ",", "additional_parameters", ",", "*", "args", ")", "root", "=", "\"/#{name.to_s}\"", "if", "args", ".", "empty?", "elsif", "args", ".", "size", "==", "1", "if", "args", ".", "first", ".", "to_s", "=~", "/", "\\d", "/", "id_metadata", "=", "find_id_metadata", "(", "name", ".", "to_s", ")", "root", "<<", "build_id_path", "(", "args", ".", "first", ",", "id_metadata", ")", "else", "root", "<<", "\"(#{args.first})\"", "end", "else", "root", "<<", "\"(#{args.join(',')})\"", "end", "QueryBuilder", ".", "new", "(", "root", ",", "additional_parameters", ")", "end" ]
Constructs a QueryBuilder instance for a collection using the arguments provided. @param [String] name the name of the collection @param [Hash] additional_parameters the additional parameters @param [Array] args the arguments to use for query
[ "Constructs", "a", "QueryBuilder", "instance", "for", "a", "collection", "using", "the", "arguments", "provided", "." ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L178-L193
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.build_collections_and_classes
def build_collections_and_classes @classes = Hash.new @class_metadata = Hash.new # This is used to store property information about a class # Build complex types first, these will be used for entities complex_types = @edmx.xpath("//edm:ComplexType", @ds_namespaces) || [] complex_types.each do |c| name = qualify_class_name(c['Name']) props = c.xpath(".//edm:Property", @ds_namespaces) methods = props.collect { |p| p['Name'] } # Standard Properties @classes[name] = ClassBuilder.new(name, methods, [], self, @namespace).build unless @classes.keys.include?(name) end entity_types = @edmx.xpath("//edm:EntityType", @ds_namespaces) entity_types.each do |e| next if e['Abstract'] == "true" klass_name = qualify_class_name(e['Name']) methods = collect_properties(klass_name, e, @edmx) nav_props = collect_navigation_properties(klass_name, e, @edmx) @classes[klass_name] = ClassBuilder.new(klass_name, methods, nav_props, self, @namespace).build unless @classes.keys.include?(klass_name) end # Fill in the collections instance variable collections = @edmx.xpath("//edm:EntityContainer/edm:EntitySet", @ds_namespaces) collections.each do |c| entity_type = c["EntityType"] @collections[c["Name"]] = { :edmx_type => entity_type, :type => convert_to_local_type(entity_type) } end build_function_imports end
ruby
def build_collections_and_classes @classes = Hash.new @class_metadata = Hash.new # This is used to store property information about a class # Build complex types first, these will be used for entities complex_types = @edmx.xpath("//edm:ComplexType", @ds_namespaces) || [] complex_types.each do |c| name = qualify_class_name(c['Name']) props = c.xpath(".//edm:Property", @ds_namespaces) methods = props.collect { |p| p['Name'] } # Standard Properties @classes[name] = ClassBuilder.new(name, methods, [], self, @namespace).build unless @classes.keys.include?(name) end entity_types = @edmx.xpath("//edm:EntityType", @ds_namespaces) entity_types.each do |e| next if e['Abstract'] == "true" klass_name = qualify_class_name(e['Name']) methods = collect_properties(klass_name, e, @edmx) nav_props = collect_navigation_properties(klass_name, e, @edmx) @classes[klass_name] = ClassBuilder.new(klass_name, methods, nav_props, self, @namespace).build unless @classes.keys.include?(klass_name) end # Fill in the collections instance variable collections = @edmx.xpath("//edm:EntityContainer/edm:EntitySet", @ds_namespaces) collections.each do |c| entity_type = c["EntityType"] @collections[c["Name"]] = { :edmx_type => entity_type, :type => convert_to_local_type(entity_type) } end build_function_imports end
[ "def", "build_collections_and_classes", "@classes", "=", "Hash", ".", "new", "@class_metadata", "=", "Hash", ".", "new", "complex_types", "=", "@edmx", ".", "xpath", "(", "\"//edm:ComplexType\"", ",", "@ds_namespaces", ")", "||", "[", "]", "complex_types", ".", "each", "do", "|", "c", "|", "name", "=", "qualify_class_name", "(", "c", "[", "'Name'", "]", ")", "props", "=", "c", ".", "xpath", "(", "\".//edm:Property\"", ",", "@ds_namespaces", ")", "methods", "=", "props", ".", "collect", "{", "|", "p", "|", "p", "[", "'Name'", "]", "}", "@classes", "[", "name", "]", "=", "ClassBuilder", ".", "new", "(", "name", ",", "methods", ",", "[", "]", ",", "self", ",", "@namespace", ")", ".", "build", "unless", "@classes", ".", "keys", ".", "include?", "(", "name", ")", "end", "entity_types", "=", "@edmx", ".", "xpath", "(", "\"//edm:EntityType\"", ",", "@ds_namespaces", ")", "entity_types", ".", "each", "do", "|", "e", "|", "next", "if", "e", "[", "'Abstract'", "]", "==", "\"true\"", "klass_name", "=", "qualify_class_name", "(", "e", "[", "'Name'", "]", ")", "methods", "=", "collect_properties", "(", "klass_name", ",", "e", ",", "@edmx", ")", "nav_props", "=", "collect_navigation_properties", "(", "klass_name", ",", "e", ",", "@edmx", ")", "@classes", "[", "klass_name", "]", "=", "ClassBuilder", ".", "new", "(", "klass_name", ",", "methods", ",", "nav_props", ",", "self", ",", "@namespace", ")", ".", "build", "unless", "@classes", ".", "keys", ".", "include?", "(", "klass_name", ")", "end", "collections", "=", "@edmx", ".", "xpath", "(", "\"//edm:EntityContainer/edm:EntitySet\"", ",", "@ds_namespaces", ")", "collections", ".", "each", "do", "|", "c", "|", "entity_type", "=", "c", "[", "\"EntityType\"", "]", "@collections", "[", "c", "[", "\"Name\"", "]", "]", "=", "{", ":edmx_type", "=>", "entity_type", ",", ":type", "=>", "convert_to_local_type", "(", "entity_type", ")", "}", "end", "build_function_imports", "end" ]
Build the classes required by the metadata
[ "Build", "the", "classes", "required", "by", "the", "metadata" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L262-L292
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.build_function_imports
def build_function_imports # Fill in the function imports functions = @edmx.xpath("//edm:EntityContainer/edm:FunctionImport", @ds_namespaces) functions.each do |f| http_method_attribute = f.xpath("@m:HttpMethod", @ds_namespaces).first # HttpMethod is no longer required http://www.odata.org/2011/10/actions-in-odata/ is_side_effecting_attribute = f.xpath("@edm:IsSideEffecting", @ds_namespaces).first http_method = 'POST' # default to POST if http_method_attribute http_method = http_method_attribute.content elsif is_side_effecting_attribute is_side_effecting = is_side_effecting_attribute.content http_method = is_side_effecting ? 'POST' : 'GET' end return_type = f["ReturnType"] inner_return_type = nil unless return_type.nil? return_type = (return_type =~ /^Collection/) ? Array : convert_to_local_type(return_type) if f["ReturnType"] =~ /\((.*)\)/ inner_return_type = convert_to_local_type($~[1]) end end params = f.xpath("edm:Parameter", @ds_namespaces) parameters = nil if params.length > 0 parameters = {} params.each do |p| parameters[p["Name"]] = p["Type"] end end @function_imports[f["Name"]] = { :http_method => http_method, :return_type => return_type, :inner_return_type => inner_return_type, :parameters => parameters } end end
ruby
def build_function_imports # Fill in the function imports functions = @edmx.xpath("//edm:EntityContainer/edm:FunctionImport", @ds_namespaces) functions.each do |f| http_method_attribute = f.xpath("@m:HttpMethod", @ds_namespaces).first # HttpMethod is no longer required http://www.odata.org/2011/10/actions-in-odata/ is_side_effecting_attribute = f.xpath("@edm:IsSideEffecting", @ds_namespaces).first http_method = 'POST' # default to POST if http_method_attribute http_method = http_method_attribute.content elsif is_side_effecting_attribute is_side_effecting = is_side_effecting_attribute.content http_method = is_side_effecting ? 'POST' : 'GET' end return_type = f["ReturnType"] inner_return_type = nil unless return_type.nil? return_type = (return_type =~ /^Collection/) ? Array : convert_to_local_type(return_type) if f["ReturnType"] =~ /\((.*)\)/ inner_return_type = convert_to_local_type($~[1]) end end params = f.xpath("edm:Parameter", @ds_namespaces) parameters = nil if params.length > 0 parameters = {} params.each do |p| parameters[p["Name"]] = p["Type"] end end @function_imports[f["Name"]] = { :http_method => http_method, :return_type => return_type, :inner_return_type => inner_return_type, :parameters => parameters } end end
[ "def", "build_function_imports", "functions", "=", "@edmx", ".", "xpath", "(", "\"//edm:EntityContainer/edm:FunctionImport\"", ",", "@ds_namespaces", ")", "functions", ".", "each", "do", "|", "f", "|", "http_method_attribute", "=", "f", ".", "xpath", "(", "\"@m:HttpMethod\"", ",", "@ds_namespaces", ")", ".", "first", "is_side_effecting_attribute", "=", "f", ".", "xpath", "(", "\"@edm:IsSideEffecting\"", ",", "@ds_namespaces", ")", ".", "first", "http_method", "=", "'POST'", "if", "http_method_attribute", "http_method", "=", "http_method_attribute", ".", "content", "elsif", "is_side_effecting_attribute", "is_side_effecting", "=", "is_side_effecting_attribute", ".", "content", "http_method", "=", "is_side_effecting", "?", "'POST'", ":", "'GET'", "end", "return_type", "=", "f", "[", "\"ReturnType\"", "]", "inner_return_type", "=", "nil", "unless", "return_type", ".", "nil?", "return_type", "=", "(", "return_type", "=~", "/", "/", ")", "?", "Array", ":", "convert_to_local_type", "(", "return_type", ")", "if", "f", "[", "\"ReturnType\"", "]", "=~", "/", "\\(", "\\)", "/", "inner_return_type", "=", "convert_to_local_type", "(", "$~", "[", "1", "]", ")", "end", "end", "params", "=", "f", ".", "xpath", "(", "\"edm:Parameter\"", ",", "@ds_namespaces", ")", "parameters", "=", "nil", "if", "params", ".", "length", ">", "0", "parameters", "=", "{", "}", "params", ".", "each", "do", "|", "p", "|", "parameters", "[", "p", "[", "\"Name\"", "]", "]", "=", "p", "[", "\"Type\"", "]", "end", "end", "@function_imports", "[", "f", "[", "\"Name\"", "]", "]", "=", "{", ":http_method", "=>", "http_method", ",", ":return_type", "=>", "return_type", ",", ":inner_return_type", "=>", "inner_return_type", ",", ":parameters", "=>", "parameters", "}", "end", "end" ]
Parses the function imports and fills the @function_imports collection
[ "Parses", "the", "function", "imports", "and", "fills", "the" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L295-L333
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.convert_to_local_type
def convert_to_local_type(edmx_type) return edm_to_ruby_type(edmx_type) if edmx_type =~ /^Edm/ klass_name = qualify_class_name(edmx_type.split('.').last) klass_name.camelize.constantize end
ruby
def convert_to_local_type(edmx_type) return edm_to_ruby_type(edmx_type) if edmx_type =~ /^Edm/ klass_name = qualify_class_name(edmx_type.split('.').last) klass_name.camelize.constantize end
[ "def", "convert_to_local_type", "(", "edmx_type", ")", "return", "edm_to_ruby_type", "(", "edmx_type", ")", "if", "edmx_type", "=~", "/", "/", "klass_name", "=", "qualify_class_name", "(", "edmx_type", ".", "split", "(", "'.'", ")", ".", "last", ")", "klass_name", ".", "camelize", ".", "constantize", "end" ]
Converts the EDMX model type to the local model type
[ "Converts", "the", "EDMX", "model", "type", "to", "the", "local", "model", "type" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L336-L340
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.build_property_metadata
def build_property_metadata(props, keys=[]) metadata = {} props.each do |property_element| prop_meta = PropertyMetadata.new(property_element) prop_meta.is_key = keys.include?(prop_meta.name) # If this is a navigation property, we need to add the association to the property metadata prop_meta.association = Association.new(property_element, @edmx) if prop_meta.nav_prop metadata[prop_meta.name] = prop_meta end metadata end
ruby
def build_property_metadata(props, keys=[]) metadata = {} props.each do |property_element| prop_meta = PropertyMetadata.new(property_element) prop_meta.is_key = keys.include?(prop_meta.name) # If this is a navigation property, we need to add the association to the property metadata prop_meta.association = Association.new(property_element, @edmx) if prop_meta.nav_prop metadata[prop_meta.name] = prop_meta end metadata end
[ "def", "build_property_metadata", "(", "props", ",", "keys", "=", "[", "]", ")", "metadata", "=", "{", "}", "props", ".", "each", "do", "|", "property_element", "|", "prop_meta", "=", "PropertyMetadata", ".", "new", "(", "property_element", ")", "prop_meta", ".", "is_key", "=", "keys", ".", "include?", "(", "prop_meta", ".", "name", ")", "prop_meta", ".", "association", "=", "Association", ".", "new", "(", "property_element", ",", "@edmx", ")", "if", "prop_meta", ".", "nav_prop", "metadata", "[", "prop_meta", ".", "name", "]", "=", "prop_meta", "end", "metadata", "end" ]
Builds the metadata need for each property for things like feed customizations and navigation properties
[ "Builds", "the", "metadata", "need", "for", "each", "property", "for", "things", "like", "feed", "customizations", "and", "navigation", "properties" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L353-L364
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.handle_collection_result
def handle_collection_result(result) results = build_classes_from_result(result) while partial? && @options[:eager_partial] results.concat handle_partial end results end
ruby
def handle_collection_result(result) results = build_classes_from_result(result) while partial? && @options[:eager_partial] results.concat handle_partial end results end
[ "def", "handle_collection_result", "(", "result", ")", "results", "=", "build_classes_from_result", "(", "result", ")", "while", "partial?", "&&", "@options", "[", ":eager_partial", "]", "results", ".", "concat", "handle_partial", "end", "results", "end" ]
Handle parsing of OData Atom result and return an array of Entry classes
[ "Handle", "parsing", "of", "OData", "Atom", "result", "and", "return", "an", "array", "of", "Entry", "classes" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L367-L373
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.handle_exception
def handle_exception(e) raise e unless defined?(e.response) && e.response != nil code = e.response[:status] error = Nokogiri::XML(e.response[:body]) message = if error.xpath("m:error/m:message", @ds_namespaces).first error.xpath("m:error/m:message", @ds_namespaces).first.content else "Server returned error but no message." end raise ServiceError.new(code), message end
ruby
def handle_exception(e) raise e unless defined?(e.response) && e.response != nil code = e.response[:status] error = Nokogiri::XML(e.response[:body]) message = if error.xpath("m:error/m:message", @ds_namespaces).first error.xpath("m:error/m:message", @ds_namespaces).first.content else "Server returned error but no message." end raise ServiceError.new(code), message end
[ "def", "handle_exception", "(", "e", ")", "raise", "e", "unless", "defined?", "(", "e", ".", "response", ")", "&&", "e", ".", "response", "!=", "nil", "code", "=", "e", ".", "response", "[", ":status", "]", "error", "=", "Nokogiri", "::", "XML", "(", "e", ".", "response", "[", ":body", "]", ")", "message", "=", "if", "error", ".", "xpath", "(", "\"m:error/m:message\"", ",", "@ds_namespaces", ")", ".", "first", "error", ".", "xpath", "(", "\"m:error/m:message\"", ",", "@ds_namespaces", ")", ".", "first", ".", "content", "else", "\"Server returned error but no message.\"", "end", "raise", "ServiceError", ".", "new", "(", "code", ")", ",", "message", "end" ]
Handles errors from the OData service
[ "Handles", "errors", "from", "the", "OData", "service" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L376-L388
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.collect_navigation_properties
def collect_navigation_properties(klass_name, element, doc) nav_props = element.xpath(".//edm:NavigationProperty", @ds_namespaces) @class_metadata[klass_name].merge!(build_property_metadata(nav_props)) nav_props.collect { |p| p['Name'] } end
ruby
def collect_navigation_properties(klass_name, element, doc) nav_props = element.xpath(".//edm:NavigationProperty", @ds_namespaces) @class_metadata[klass_name].merge!(build_property_metadata(nav_props)) nav_props.collect { |p| p['Name'] } end
[ "def", "collect_navigation_properties", "(", "klass_name", ",", "element", ",", "doc", ")", "nav_props", "=", "element", ".", "xpath", "(", "\".//edm:NavigationProperty\"", ",", "@ds_namespaces", ")", "@class_metadata", "[", "klass_name", "]", ".", "merge!", "(", "build_property_metadata", "(", "nav_props", ")", ")", "nav_props", ".", "collect", "{", "|", "p", "|", "p", "[", "'Name'", "]", "}", "end" ]
Similar to +collect_properties+, but handles the navigation properties
[ "Similar", "to", "+", "collect_properties", "+", "but", "handles", "the", "navigation", "properties" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L408-L412
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.build_classes_from_result
def build_classes_from_result(result) doc = Nokogiri::XML(result) is_links = doc.at_xpath("/ds:links", @ds_namespaces) return parse_link_results(doc) if is_links entries = doc.xpath("//atom:entry[not(ancestor::atom:entry)]", @ds_namespaces) extract_partial(doc) results = [] entries.each do |entry| results << entry_to_class(entry) end return results end
ruby
def build_classes_from_result(result) doc = Nokogiri::XML(result) is_links = doc.at_xpath("/ds:links", @ds_namespaces) return parse_link_results(doc) if is_links entries = doc.xpath("//atom:entry[not(ancestor::atom:entry)]", @ds_namespaces) extract_partial(doc) results = [] entries.each do |entry| results << entry_to_class(entry) end return results end
[ "def", "build_classes_from_result", "(", "result", ")", "doc", "=", "Nokogiri", "::", "XML", "(", "result", ")", "is_links", "=", "doc", ".", "at_xpath", "(", "\"/ds:links\"", ",", "@ds_namespaces", ")", "return", "parse_link_results", "(", "doc", ")", "if", "is_links", "entries", "=", "doc", ".", "xpath", "(", "\"//atom:entry[not(ancestor::atom:entry)]\"", ",", "@ds_namespaces", ")", "extract_partial", "(", "doc", ")", "results", "=", "[", "]", "entries", ".", "each", "do", "|", "entry", "|", "results", "<<", "entry_to_class", "(", "entry", ")", "end", "return", "results", "end" ]
Helper to loop through a result and create an instance for each entity in the results
[ "Helper", "to", "loop", "through", "a", "result", "and", "create", "an", "instance", "for", "each", "entity", "in", "the", "results" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L415-L430
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.entry_to_class
def entry_to_class(entry) # Retrieve the class name from the fully qualified name (the last string after the last dot) klass_name = entry.xpath("./atom:category/@term", @ds_namespaces).to_s.split('.')[-1] # Is the category missing? See if there is a title that we can use to build the class if klass_name.nil? title = entry.xpath("./atom:title", @ds_namespaces).first return nil if title.nil? klass_name = title.content.to_s end return nil if klass_name.nil? properties = entry.xpath("./atom:content/m:properties/*", @ds_namespaces) klass = @classes[qualify_class_name(klass_name)].new # Fill metadata meta_id = entry.xpath("./atom:id", @ds_namespaces)[0].content klass.send :__metadata=, { :uri => meta_id } # Fill properties for prop in properties prop_name = prop.name klass.send "#{prop_name}=", parse_value_xml(prop) end # Fill properties represented outside of the properties collection @class_metadata[qualify_class_name(klass_name)].select { |k,v| v.fc_keep_in_content == false }.each do |k, meta| if meta.fc_target_path == "SyndicationTitle" title = entry.xpath("./atom:title", @ds_namespaces).first klass.send "#{meta.name}=", title.content elsif meta.fc_target_path == "SyndicationSummary" summary = entry.xpath("./atom:summary", @ds_namespaces).first klass.send "#{meta.name}=", summary.content end end inline_links = entry.xpath("./atom:link[m:inline]", @ds_namespaces) for link in inline_links # TODO: Use the metadata's associations to determine the multiplicity instead of this "hack" property_name = link.attributes['title'].to_s if singular?(property_name) inline_entry = link.xpath("./m:inline/atom:entry", @ds_namespaces).first inline_klass = build_inline_class(klass, inline_entry, property_name) klass.send "#{property_name}=", inline_klass else inline_classes, inline_entries = [], link.xpath("./m:inline/atom:feed/atom:entry", @ds_namespaces) for inline_entry in inline_entries # Build the class inline_klass = entry_to_class(inline_entry) # Add the property to the temp collection inline_classes << inline_klass end # Assign the array of classes to the property property_name = link.xpath("@title", @ds_namespaces) klass.send "#{property_name}=", inline_classes end end klass end
ruby
def entry_to_class(entry) # Retrieve the class name from the fully qualified name (the last string after the last dot) klass_name = entry.xpath("./atom:category/@term", @ds_namespaces).to_s.split('.')[-1] # Is the category missing? See if there is a title that we can use to build the class if klass_name.nil? title = entry.xpath("./atom:title", @ds_namespaces).first return nil if title.nil? klass_name = title.content.to_s end return nil if klass_name.nil? properties = entry.xpath("./atom:content/m:properties/*", @ds_namespaces) klass = @classes[qualify_class_name(klass_name)].new # Fill metadata meta_id = entry.xpath("./atom:id", @ds_namespaces)[0].content klass.send :__metadata=, { :uri => meta_id } # Fill properties for prop in properties prop_name = prop.name klass.send "#{prop_name}=", parse_value_xml(prop) end # Fill properties represented outside of the properties collection @class_metadata[qualify_class_name(klass_name)].select { |k,v| v.fc_keep_in_content == false }.each do |k, meta| if meta.fc_target_path == "SyndicationTitle" title = entry.xpath("./atom:title", @ds_namespaces).first klass.send "#{meta.name}=", title.content elsif meta.fc_target_path == "SyndicationSummary" summary = entry.xpath("./atom:summary", @ds_namespaces).first klass.send "#{meta.name}=", summary.content end end inline_links = entry.xpath("./atom:link[m:inline]", @ds_namespaces) for link in inline_links # TODO: Use the metadata's associations to determine the multiplicity instead of this "hack" property_name = link.attributes['title'].to_s if singular?(property_name) inline_entry = link.xpath("./m:inline/atom:entry", @ds_namespaces).first inline_klass = build_inline_class(klass, inline_entry, property_name) klass.send "#{property_name}=", inline_klass else inline_classes, inline_entries = [], link.xpath("./m:inline/atom:feed/atom:entry", @ds_namespaces) for inline_entry in inline_entries # Build the class inline_klass = entry_to_class(inline_entry) # Add the property to the temp collection inline_classes << inline_klass end # Assign the array of classes to the property property_name = link.xpath("@title", @ds_namespaces) klass.send "#{property_name}=", inline_classes end end klass end
[ "def", "entry_to_class", "(", "entry", ")", "klass_name", "=", "entry", ".", "xpath", "(", "\"./atom:category/@term\"", ",", "@ds_namespaces", ")", ".", "to_s", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "if", "klass_name", ".", "nil?", "title", "=", "entry", ".", "xpath", "(", "\"./atom:title\"", ",", "@ds_namespaces", ")", ".", "first", "return", "nil", "if", "title", ".", "nil?", "klass_name", "=", "title", ".", "content", ".", "to_s", "end", "return", "nil", "if", "klass_name", ".", "nil?", "properties", "=", "entry", ".", "xpath", "(", "\"./atom:content/m:properties/*\"", ",", "@ds_namespaces", ")", "klass", "=", "@classes", "[", "qualify_class_name", "(", "klass_name", ")", "]", ".", "new", "meta_id", "=", "entry", ".", "xpath", "(", "\"./atom:id\"", ",", "@ds_namespaces", ")", "[", "0", "]", ".", "content", "klass", ".", "send", ":__metadata=", ",", "{", ":uri", "=>", "meta_id", "}", "for", "prop", "in", "properties", "prop_name", "=", "prop", ".", "name", "klass", ".", "send", "\"#{prop_name}=\"", ",", "parse_value_xml", "(", "prop", ")", "end", "@class_metadata", "[", "qualify_class_name", "(", "klass_name", ")", "]", ".", "select", "{", "|", "k", ",", "v", "|", "v", ".", "fc_keep_in_content", "==", "false", "}", ".", "each", "do", "|", "k", ",", "meta", "|", "if", "meta", ".", "fc_target_path", "==", "\"SyndicationTitle\"", "title", "=", "entry", ".", "xpath", "(", "\"./atom:title\"", ",", "@ds_namespaces", ")", ".", "first", "klass", ".", "send", "\"#{meta.name}=\"", ",", "title", ".", "content", "elsif", "meta", ".", "fc_target_path", "==", "\"SyndicationSummary\"", "summary", "=", "entry", ".", "xpath", "(", "\"./atom:summary\"", ",", "@ds_namespaces", ")", ".", "first", "klass", ".", "send", "\"#{meta.name}=\"", ",", "summary", ".", "content", "end", "end", "inline_links", "=", "entry", ".", "xpath", "(", "\"./atom:link[m:inline]\"", ",", "@ds_namespaces", ")", "for", "link", "in", "inline_links", "property_name", "=", "link", ".", "attributes", "[", "'title'", "]", ".", "to_s", "if", "singular?", "(", "property_name", ")", "inline_entry", "=", "link", ".", "xpath", "(", "\"./m:inline/atom:entry\"", ",", "@ds_namespaces", ")", ".", "first", "inline_klass", "=", "build_inline_class", "(", "klass", ",", "inline_entry", ",", "property_name", ")", "klass", ".", "send", "\"#{property_name}=\"", ",", "inline_klass", "else", "inline_classes", ",", "inline_entries", "=", "[", "]", ",", "link", ".", "xpath", "(", "\"./m:inline/atom:feed/atom:entry\"", ",", "@ds_namespaces", ")", "for", "inline_entry", "in", "inline_entries", "inline_klass", "=", "entry_to_class", "(", "inline_entry", ")", "inline_classes", "<<", "inline_klass", "end", "property_name", "=", "link", ".", "xpath", "(", "\"@title\"", ",", "@ds_namespaces", ")", "klass", ".", "send", "\"#{property_name}=\"", ",", "inline_classes", "end", "end", "klass", "end" ]
Converts an XML Entry into a class
[ "Converts", "an", "XML", "Entry", "into", "a", "class" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L433-L497
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.extract_partial
def extract_partial(doc) next_links = doc.xpath('//atom:link[@rel="next"]', @ds_namespaces) @has_partial = next_links.any? if @has_partial uri = Addressable::URI.parse(next_links[0]['href']) uri.query_values = uri.query_values.merge @additional_params unless @additional_params.empty? @next_uri = uri.to_s end end
ruby
def extract_partial(doc) next_links = doc.xpath('//atom:link[@rel="next"]', @ds_namespaces) @has_partial = next_links.any? if @has_partial uri = Addressable::URI.parse(next_links[0]['href']) uri.query_values = uri.query_values.merge @additional_params unless @additional_params.empty? @next_uri = uri.to_s end end
[ "def", "extract_partial", "(", "doc", ")", "next_links", "=", "doc", ".", "xpath", "(", "'//atom:link[@rel=\"next\"]'", ",", "@ds_namespaces", ")", "@has_partial", "=", "next_links", ".", "any?", "if", "@has_partial", "uri", "=", "Addressable", "::", "URI", ".", "parse", "(", "next_links", "[", "0", "]", "[", "'href'", "]", ")", "uri", ".", "query_values", "=", "uri", ".", "query_values", ".", "merge", "@additional_params", "unless", "@additional_params", ".", "empty?", "@next_uri", "=", "uri", ".", "to_s", "end", "end" ]
Tests for and extracts the next href of a partial
[ "Tests", "for", "and", "extracts", "the", "next", "href", "of", "a", "partial" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L500-L508
train
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.parse_link_results
def parse_link_results(doc) uris = doc.xpath("/ds:links/ds:uri", @ds_namespaces) results = [] uris.each do |uri_el| link = uri_el.content results << URI.parse(link) end results end
ruby
def parse_link_results(doc) uris = doc.xpath("/ds:links/ds:uri", @ds_namespaces) results = [] uris.each do |uri_el| link = uri_el.content results << URI.parse(link) end results end
[ "def", "parse_link_results", "(", "doc", ")", "uris", "=", "doc", ".", "xpath", "(", "\"/ds:links/ds:uri\"", ",", "@ds_namespaces", ")", "results", "=", "[", "]", "uris", ".", "each", "do", "|", "uri_el", "|", "link", "=", "uri_el", ".", "content", "results", "<<", "URI", ".", "parse", "(", "link", ")", "end", "results", "end" ]
Handle link results
[ "Handle", "link", "results" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L519-L527
train