id
int32
0
24.9k
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
22,100
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?", "# 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" ]
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
22,101
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
22,102
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
22,103
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
22,104
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
22,105
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
22,106
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
22,107
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
22,108
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", "# 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" ]
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
22,109
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", "=", "{", "}", "# 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" ]
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
22,110
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
22,111
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
22,112
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
22,113
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
22,114
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
22,115
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
22,116
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
22,117
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
22,118
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
22,119
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
22,120
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
22,121
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
22,122
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
22,123
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
22,124
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", "# 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" ]
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
22,125
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
22,126
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", "# 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" ]
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
22,127
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
22,128
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
22,129
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
22,130
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
22,131
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
22,132
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
22,133
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
22,134
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
22,135
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
22,136
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
22,137
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
22,138
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
22,139
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
22,140
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", "=", "[", "]", "# 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" ]
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
22,141
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
22,142
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
22,143
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", ")", "# 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" ]
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
22,144
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", "# 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" ]
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
22,145
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?", "#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" ]
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
22,146
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
22,147
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
22,148
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
22,149
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
22,150
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
22,151
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", "# 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" ]
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
22,152
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
22,153
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
22,154
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
22,155
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
22,156
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!", "# :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" ]
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
22,157
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", ")", "# Queries", "if", "@collections", ".", "include?", "(", "name", ".", "to_s", ")", "@query", "=", "build_collection_query_object", "(", "name", ",", "@additional_params", ",", "args", ")", "return", "@query", "# Adds", "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
22,158
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
22,159
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", "# Adds", "elsif", "method", ".", "to_s", "=~", "/", "/", "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" ]
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
22,160
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
22,161
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
22,162
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?", "#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" ]
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
22,163
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", "# 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" ]
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
22,164
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", "# 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", "=~", "/", "/", ")", "?", "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
22,165
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
22,166
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", ")", "# 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" ]
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
22,167
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
22,168
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
22,169
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
22,170
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
22,171
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", ")", "# 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" ]
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
22,172
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
22,173
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
22,174
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.link_child_to_parent
def link_child_to_parent(operation) child_collection = operation.klass.send("#{operation.klass_name}") || [] child_collection << operation.child_klass operation.klass.send("#{operation.klass_name}=", child_collection) # Attach the parent to the child parent_meta = @class_metadata[operation.klass.class.to_s][operation.klass_name] child_meta = @class_metadata[operation.child_klass.class.to_s] # Find the matching relationship on the child object child_properties = Helpers.normalize_to_hash( child_meta.select { |k, prop| prop.nav_prop && prop.association.relationship == parent_meta.association.relationship }) child_property_to_set = child_properties.keys.first # There should be only one match # TODO: Handle many to many scenarios where the child property is an enumerable operation.child_klass.send("#{child_property_to_set}=", operation.klass) end
ruby
def link_child_to_parent(operation) child_collection = operation.klass.send("#{operation.klass_name}") || [] child_collection << operation.child_klass operation.klass.send("#{operation.klass_name}=", child_collection) # Attach the parent to the child parent_meta = @class_metadata[operation.klass.class.to_s][operation.klass_name] child_meta = @class_metadata[operation.child_klass.class.to_s] # Find the matching relationship on the child object child_properties = Helpers.normalize_to_hash( child_meta.select { |k, prop| prop.nav_prop && prop.association.relationship == parent_meta.association.relationship }) child_property_to_set = child_properties.keys.first # There should be only one match # TODO: Handle many to many scenarios where the child property is an enumerable operation.child_klass.send("#{child_property_to_set}=", operation.klass) end
[ "def", "link_child_to_parent", "(", "operation", ")", "child_collection", "=", "operation", ".", "klass", ".", "send", "(", "\"#{operation.klass_name}\"", ")", "||", "[", "]", "child_collection", "<<", "operation", ".", "child_klass", "operation", ".", "klass", ".", "send", "(", "\"#{operation.klass_name}=\"", ",", "child_collection", ")", "# Attach the parent to the child", "parent_meta", "=", "@class_metadata", "[", "operation", ".", "klass", ".", "class", ".", "to_s", "]", "[", "operation", ".", "klass_name", "]", "child_meta", "=", "@class_metadata", "[", "operation", ".", "child_klass", ".", "class", ".", "to_s", "]", "# Find the matching relationship on the child object", "child_properties", "=", "Helpers", ".", "normalize_to_hash", "(", "child_meta", ".", "select", "{", "|", "k", ",", "prop", "|", "prop", ".", "nav_prop", "&&", "prop", ".", "association", ".", "relationship", "==", "parent_meta", ".", "association", ".", "relationship", "}", ")", "child_property_to_set", "=", "child_properties", ".", "keys", ".", "first", "# There should be only one match", "# TODO: Handle many to many scenarios where the child property is an enumerable", "operation", ".", "child_klass", ".", "send", "(", "\"#{child_property_to_set}=\"", ",", "operation", ".", "klass", ")", "end" ]
Used to link a child object to its parent and vice-versa after a add_link operation
[ "Used", "to", "link", "a", "child", "object", "to", "its", "parent", "and", "vice", "-", "versa", "after", "a", "add_link", "operation" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L580-L597
22,175
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.fill_complex_type_properties
def fill_complex_type_properties(complex_type_xml, klass) properties = complex_type_xml.xpath(".//*") properties.each do |prop| klass.send "#{prop.name}=", parse_value_xml(prop) end end
ruby
def fill_complex_type_properties(complex_type_xml, klass) properties = complex_type_xml.xpath(".//*") properties.each do |prop| klass.send "#{prop.name}=", parse_value_xml(prop) end end
[ "def", "fill_complex_type_properties", "(", "complex_type_xml", ",", "klass", ")", "properties", "=", "complex_type_xml", ".", "xpath", "(", "\".//*\"", ")", "properties", ".", "each", "do", "|", "prop", "|", "klass", ".", "send", "\"#{prop.name}=\"", ",", "parse_value_xml", "(", "prop", ")", "end", "end" ]
Helper method for complex_type_to_class
[ "Helper", "method", "for", "complex_type_to_class" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L736-L741
22,176
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.parse_date
def parse_date(sdate) # Assume this is UTC if no timezone is specified sdate = sdate + "Z" unless sdate.match(/Z|([+|-]\d{2}:\d{2})$/) # This is to handle older versions of Ruby (e.g. ruby 1.8.7 (2010-12-23 patchlevel 330) [i386-mingw32]) # See http://makandra.com/notes/1017-maximum-representable-value-for-a-ruby-time-object # In recent versions of Ruby, Time has a much larger range begin result = Time.parse(sdate) rescue ArgumentError result = DateTime.parse(sdate) end return result end
ruby
def parse_date(sdate) # Assume this is UTC if no timezone is specified sdate = sdate + "Z" unless sdate.match(/Z|([+|-]\d{2}:\d{2})$/) # This is to handle older versions of Ruby (e.g. ruby 1.8.7 (2010-12-23 patchlevel 330) [i386-mingw32]) # See http://makandra.com/notes/1017-maximum-representable-value-for-a-ruby-time-object # In recent versions of Ruby, Time has a much larger range begin result = Time.parse(sdate) rescue ArgumentError result = DateTime.parse(sdate) end return result end
[ "def", "parse_date", "(", "sdate", ")", "# Assume this is UTC if no timezone is specified", "sdate", "=", "sdate", "+", "\"Z\"", "unless", "sdate", ".", "match", "(", "/", "\\d", "\\d", "/", ")", "# This is to handle older versions of Ruby (e.g. ruby 1.8.7 (2010-12-23 patchlevel 330) [i386-mingw32])", "# See http://makandra.com/notes/1017-maximum-representable-value-for-a-ruby-time-object", "# In recent versions of Ruby, Time has a much larger range", "begin", "result", "=", "Time", ".", "parse", "(", "sdate", ")", "rescue", "ArgumentError", "result", "=", "DateTime", ".", "parse", "(", "sdate", ")", "end", "return", "result", "end" ]
Field Converters Handles parsing datetimes from a string
[ "Field", "Converters", "Handles", "parsing", "datetimes", "from", "a", "string" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L746-L760
22,177
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.parse_value_xml
def parse_value_xml(property_xml) property_type = Helpers.get_namespaced_attribute(property_xml, 'type', 'm') property_null = Helpers.get_namespaced_attribute(property_xml, 'null', 'm') if property_type.nil? || (property_type && property_type.match(/^Edm/)) return parse_value(property_xml.content, property_type, property_null) end complex_type_to_class(property_xml) end
ruby
def parse_value_xml(property_xml) property_type = Helpers.get_namespaced_attribute(property_xml, 'type', 'm') property_null = Helpers.get_namespaced_attribute(property_xml, 'null', 'm') if property_type.nil? || (property_type && property_type.match(/^Edm/)) return parse_value(property_xml.content, property_type, property_null) end complex_type_to_class(property_xml) end
[ "def", "parse_value_xml", "(", "property_xml", ")", "property_type", "=", "Helpers", ".", "get_namespaced_attribute", "(", "property_xml", ",", "'type'", ",", "'m'", ")", "property_null", "=", "Helpers", ".", "get_namespaced_attribute", "(", "property_xml", ",", "'null'", ",", "'m'", ")", "if", "property_type", ".", "nil?", "||", "(", "property_type", "&&", "property_type", ".", "match", "(", "/", "/", ")", ")", "return", "parse_value", "(", "property_xml", ".", "content", ",", "property_type", ",", "property_null", ")", "end", "complex_type_to_class", "(", "property_xml", ")", "end" ]
Parses a value into the proper type based on an xml property element
[ "Parses", "a", "value", "into", "the", "proper", "type", "based", "on", "an", "xml", "property", "element" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L763-L772
22,178
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.parse_primative_type
def parse_primative_type(value, return_type) return value.to_i if return_type == Fixnum return value.to_d if return_type == Float return parse_date(value.to_s) if return_type == Time return value.to_s end
ruby
def parse_primative_type(value, return_type) return value.to_i if return_type == Fixnum return value.to_d if return_type == Float return parse_date(value.to_s) if return_type == Time return value.to_s end
[ "def", "parse_primative_type", "(", "value", ",", "return_type", ")", "return", "value", ".", "to_i", "if", "return_type", "==", "Fixnum", "return", "value", ".", "to_d", "if", "return_type", "==", "Float", "return", "parse_date", "(", "value", ".", "to_s", ")", "if", "return_type", "==", "Time", "return", "value", ".", "to_s", "end" ]
Parses a value into the proper type based on a specified return type
[ "Parses", "a", "value", "into", "the", "proper", "type", "based", "on", "a", "specified", "return", "type" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L796-L801
22,179
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.execute_import_function
def execute_import_function(name, *args) func = @function_imports[name] # Check the args making sure that more weren't passed in than the function needs param_count = func[:parameters].nil? ? 0 : func[:parameters].count arg_count = args.nil? ? 0 : args[0].count if arg_count > param_count raise ArgumentError, "wrong number of arguments (#{arg_count} for #{param_count})" end # Convert the parameters to a hash params = {} func[:parameters].keys.each_with_index { |key, i| params[key] = args[0][i] } unless func[:parameters].nil? function_uri = build_function_import_uri(name, params) result = OData::Resource.new(function_uri, @rest_options).send(func[:http_method].downcase, {}) # Is this a 204 (No content) result? return true if result.status == 204 # No? Then we need to parse the results. There are 4 kinds... if func[:return_type] == Array # a collection of entites return build_classes_from_result(result.body) if @classes.include?(func[:inner_return_type].to_s) # a collection of native types elements = Nokogiri::XML(result.body).xpath("//ds:element", @ds_namespaces) results = [] elements.each do |e| results << parse_primative_type(e.content, func[:inner_return_type]) end return results end # a single entity if @classes.include?(func[:return_type].to_s) entry = Nokogiri::XML(result.body).xpath("atom:entry[not(ancestor::atom:entry)]", @ds_namespaces) return entry_to_class(entry) end # or a single native type unless func[:return_type].nil? e = Nokogiri::XML(result.body).xpath("/*").first return parse_primative_type(e.content, func[:return_type]) end # Nothing could be parsed, so just return if we got a 200 or not return (result.status == 200) end
ruby
def execute_import_function(name, *args) func = @function_imports[name] # Check the args making sure that more weren't passed in than the function needs param_count = func[:parameters].nil? ? 0 : func[:parameters].count arg_count = args.nil? ? 0 : args[0].count if arg_count > param_count raise ArgumentError, "wrong number of arguments (#{arg_count} for #{param_count})" end # Convert the parameters to a hash params = {} func[:parameters].keys.each_with_index { |key, i| params[key] = args[0][i] } unless func[:parameters].nil? function_uri = build_function_import_uri(name, params) result = OData::Resource.new(function_uri, @rest_options).send(func[:http_method].downcase, {}) # Is this a 204 (No content) result? return true if result.status == 204 # No? Then we need to parse the results. There are 4 kinds... if func[:return_type] == Array # a collection of entites return build_classes_from_result(result.body) if @classes.include?(func[:inner_return_type].to_s) # a collection of native types elements = Nokogiri::XML(result.body).xpath("//ds:element", @ds_namespaces) results = [] elements.each do |e| results << parse_primative_type(e.content, func[:inner_return_type]) end return results end # a single entity if @classes.include?(func[:return_type].to_s) entry = Nokogiri::XML(result.body).xpath("atom:entry[not(ancestor::atom:entry)]", @ds_namespaces) return entry_to_class(entry) end # or a single native type unless func[:return_type].nil? e = Nokogiri::XML(result.body).xpath("/*").first return parse_primative_type(e.content, func[:return_type]) end # Nothing could be parsed, so just return if we got a 200 or not return (result.status == 200) end
[ "def", "execute_import_function", "(", "name", ",", "*", "args", ")", "func", "=", "@function_imports", "[", "name", "]", "# Check the args making sure that more weren't passed in than the function needs", "param_count", "=", "func", "[", ":parameters", "]", ".", "nil?", "?", "0", ":", "func", "[", ":parameters", "]", ".", "count", "arg_count", "=", "args", ".", "nil?", "?", "0", ":", "args", "[", "0", "]", ".", "count", "if", "arg_count", ">", "param_count", "raise", "ArgumentError", ",", "\"wrong number of arguments (#{arg_count} for #{param_count})\"", "end", "# Convert the parameters to a hash", "params", "=", "{", "}", "func", "[", ":parameters", "]", ".", "keys", ".", "each_with_index", "{", "|", "key", ",", "i", "|", "params", "[", "key", "]", "=", "args", "[", "0", "]", "[", "i", "]", "}", "unless", "func", "[", ":parameters", "]", ".", "nil?", "function_uri", "=", "build_function_import_uri", "(", "name", ",", "params", ")", "result", "=", "OData", "::", "Resource", ".", "new", "(", "function_uri", ",", "@rest_options", ")", ".", "send", "(", "func", "[", ":http_method", "]", ".", "downcase", ",", "{", "}", ")", "# Is this a 204 (No content) result?", "return", "true", "if", "result", ".", "status", "==", "204", "# No? Then we need to parse the results. There are 4 kinds...", "if", "func", "[", ":return_type", "]", "==", "Array", "# a collection of entites", "return", "build_classes_from_result", "(", "result", ".", "body", ")", "if", "@classes", ".", "include?", "(", "func", "[", ":inner_return_type", "]", ".", "to_s", ")", "# a collection of native types", "elements", "=", "Nokogiri", "::", "XML", "(", "result", ".", "body", ")", ".", "xpath", "(", "\"//ds:element\"", ",", "@ds_namespaces", ")", "results", "=", "[", "]", "elements", ".", "each", "do", "|", "e", "|", "results", "<<", "parse_primative_type", "(", "e", ".", "content", ",", "func", "[", ":inner_return_type", "]", ")", "end", "return", "results", "end", "# a single entity", "if", "@classes", ".", "include?", "(", "func", "[", ":return_type", "]", ".", "to_s", ")", "entry", "=", "Nokogiri", "::", "XML", "(", "result", ".", "body", ")", ".", "xpath", "(", "\"atom:entry[not(ancestor::atom:entry)]\"", ",", "@ds_namespaces", ")", "return", "entry_to_class", "(", "entry", ")", "end", "# or a single native type", "unless", "func", "[", ":return_type", "]", ".", "nil?", "e", "=", "Nokogiri", "::", "XML", "(", "result", ".", "body", ")", ".", "xpath", "(", "\"/*\"", ")", ".", "first", "return", "parse_primative_type", "(", "e", ".", "content", ",", "func", "[", ":return_type", "]", ")", "end", "# Nothing could be parsed, so just return if we got a 200 or not", "return", "(", "result", ".", "status", "==", "200", ")", "end" ]
Method Missing Handlers Executes an import function
[ "Method", "Missing", "Handlers", "Executes", "an", "import", "function" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L815-L862
22,180
visoft/ruby_odata
features/support/pickle.rb
Pickle.Session.model_with_associations
def model_with_associations(name) model = created_model(name) return nil unless model OData::PickleAdapter.get_model(model.class, model.id, true) end
ruby
def model_with_associations(name) model = created_model(name) return nil unless model OData::PickleAdapter.get_model(model.class, model.id, true) end
[ "def", "model_with_associations", "(", "name", ")", "model", "=", "created_model", "(", "name", ")", "return", "nil", "unless", "model", "OData", "::", "PickleAdapter", ".", "get_model", "(", "model", ".", "class", ",", "model", ".", "id", ",", "true", ")", "end" ]
return a newly selected model with the navigation properties expanded
[ "return", "a", "newly", "selected", "model", "with", "the", "navigation", "properties", "expanded" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/features/support/pickle.rb#L87-L91
22,181
visoft/ruby_odata
lib/ruby_odata/class_builder.rb
OData.ClassBuilder.build
def build # return if already built return @klass unless @klass.nil? # need the class name to build class return nil if @klass_name.nil? # return if we can find constant corresponding to class name already_defined = eval("defined?(#{@klass_name}) == 'constant' and #{@klass_name}.class == Class") if already_defined @klass = @klass_name.constantize return @klass end if @namespace namespaces = @namespace.split(/\.|::/) namespaces.each_with_index do |ns, index| if index == 0 next if Object.const_defined? ns Object.const_set(ns, Module.new) else current_ns = namespaces[0..index-1].join '::' next if eval "#{current_ns}.const_defined? '#{ns}'" eval "#{current_ns}.const_set('#{ns}', Module.new)" end end klass_constant = @klass_name.split('::').last eval "#{namespaces.join '::'}.const_set('#{klass_constant}', Class.new.extend(ActiveSupport::JSON))" else Object.const_set(@klass_name, Class.new.extend(ActiveSupport::JSON)) end @klass = @klass_name.constantize @klass.class_eval do include OData end add_initializer(@klass) add_methods(@klass) add_nav_props(@klass) add_class_methods(@klass) return @klass end
ruby
def build # return if already built return @klass unless @klass.nil? # need the class name to build class return nil if @klass_name.nil? # return if we can find constant corresponding to class name already_defined = eval("defined?(#{@klass_name}) == 'constant' and #{@klass_name}.class == Class") if already_defined @klass = @klass_name.constantize return @klass end if @namespace namespaces = @namespace.split(/\.|::/) namespaces.each_with_index do |ns, index| if index == 0 next if Object.const_defined? ns Object.const_set(ns, Module.new) else current_ns = namespaces[0..index-1].join '::' next if eval "#{current_ns}.const_defined? '#{ns}'" eval "#{current_ns}.const_set('#{ns}', Module.new)" end end klass_constant = @klass_name.split('::').last eval "#{namespaces.join '::'}.const_set('#{klass_constant}', Class.new.extend(ActiveSupport::JSON))" else Object.const_set(@klass_name, Class.new.extend(ActiveSupport::JSON)) end @klass = @klass_name.constantize @klass.class_eval do include OData end add_initializer(@klass) add_methods(@klass) add_nav_props(@klass) add_class_methods(@klass) return @klass end
[ "def", "build", "# return if already built", "return", "@klass", "unless", "@klass", ".", "nil?", "# need the class name to build class", "return", "nil", "if", "@klass_name", ".", "nil?", "# return if we can find constant corresponding to class name", "already_defined", "=", "eval", "(", "\"defined?(#{@klass_name}) == 'constant' and #{@klass_name}.class == Class\"", ")", "if", "already_defined", "@klass", "=", "@klass_name", ".", "constantize", "return", "@klass", "end", "if", "@namespace", "namespaces", "=", "@namespace", ".", "split", "(", "/", "\\.", "/", ")", "namespaces", ".", "each_with_index", "do", "|", "ns", ",", "index", "|", "if", "index", "==", "0", "next", "if", "Object", ".", "const_defined?", "ns", "Object", ".", "const_set", "(", "ns", ",", "Module", ".", "new", ")", "else", "current_ns", "=", "namespaces", "[", "0", "..", "index", "-", "1", "]", ".", "join", "'::'", "next", "if", "eval", "\"#{current_ns}.const_defined? '#{ns}'\"", "eval", "\"#{current_ns}.const_set('#{ns}', Module.new)\"", "end", "end", "klass_constant", "=", "@klass_name", ".", "split", "(", "'::'", ")", ".", "last", "eval", "\"#{namespaces.join '::'}.const_set('#{klass_constant}', Class.new.extend(ActiveSupport::JSON))\"", "else", "Object", ".", "const_set", "(", "@klass_name", ",", "Class", ".", "new", ".", "extend", "(", "ActiveSupport", "::", "JSON", ")", ")", "end", "@klass", "=", "@klass_name", ".", "constantize", "@klass", ".", "class_eval", "do", "include", "OData", "end", "add_initializer", "(", "@klass", ")", "add_methods", "(", "@klass", ")", "add_nav_props", "(", "@klass", ")", "add_class_methods", "(", "@klass", ")", "return", "@klass", "end" ]
Creates a new instance of the ClassBuilder class @param [String] klass_name the name/type of the class to create @param [Array] methods the accessor methods to add to the class @param [Array] nav_props the accessor methods to add for navigation properties @param [Service] context the service context that this entity belongs to @param [String, nil] namespace optional namespace to create the classes in Returns a dynamically generated class definition based on the constructor parameters
[ "Creates", "a", "new", "instance", "of", "the", "ClassBuilder", "class" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/class_builder.rb#L20-L65
22,182
visoft/ruby_odata
lib/ruby_odata/query_builder.rb
OData.QueryBuilder.links
def links(navigation_property) raise OData::NotSupportedError.new("You cannot call both the `links` method and the `count` method in the same query.") if @count raise OData::NotSupportedError.new("You cannot call both the `links` method and the `select` method in the same query.") unless @select.empty? @links_navigation_property = navigation_property self end
ruby
def links(navigation_property) raise OData::NotSupportedError.new("You cannot call both the `links` method and the `count` method in the same query.") if @count raise OData::NotSupportedError.new("You cannot call both the `links` method and the `select` method in the same query.") unless @select.empty? @links_navigation_property = navigation_property self end
[ "def", "links", "(", "navigation_property", ")", "raise", "OData", "::", "NotSupportedError", ".", "new", "(", "\"You cannot call both the `links` method and the `count` method in the same query.\"", ")", "if", "@count", "raise", "OData", "::", "NotSupportedError", ".", "new", "(", "\"You cannot call both the `links` method and the `select` method in the same query.\"", ")", "unless", "@select", ".", "empty?", "@links_navigation_property", "=", "navigation_property", "self", "end" ]
Used to return links instead of actual objects @param [String] navigation_property the NavigationProperty name to retrieve the links for @raise [NotSupportedError] if count has already been called on the query @example svc.Categories(1).links("Products") product_links = svc.execute # => returns URIs for the products under the Category with an ID of 1
[ "Used", "to", "return", "links", "instead", "of", "actual", "objects" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/query_builder.rb#L104-L109
22,183
visoft/ruby_odata
lib/ruby_odata/query_builder.rb
OData.QueryBuilder.count
def count raise OData::NotSupportedError.new("You cannot call both the `links` method and the `count` method in the same query.") if @links_navigation_property raise OData::NotSupportedError.new("You cannot call both the `select` method and the `count` method in the same query.") unless @select.empty? @count = true self end
ruby
def count raise OData::NotSupportedError.new("You cannot call both the `links` method and the `count` method in the same query.") if @links_navigation_property raise OData::NotSupportedError.new("You cannot call both the `select` method and the `count` method in the same query.") unless @select.empty? @count = true self end
[ "def", "count", "raise", "OData", "::", "NotSupportedError", ".", "new", "(", "\"You cannot call both the `links` method and the `count` method in the same query.\"", ")", "if", "@links_navigation_property", "raise", "OData", "::", "NotSupportedError", ".", "new", "(", "\"You cannot call both the `select` method and the `count` method in the same query.\"", ")", "unless", "@select", ".", "empty?", "@count", "=", "true", "self", "end" ]
Used to return a count of objects instead of the objects themselves @raise [NotSupportedError] if links has already been called on the query @example svc.Products svc.count product_count = svc.execute
[ "Used", "to", "return", "a", "count", "of", "objects", "instead", "of", "the", "objects", "themselves" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/query_builder.rb#L119-L125
22,184
visoft/ruby_odata
lib/ruby_odata/query_builder.rb
OData.QueryBuilder.select
def select(*fields) raise OData::NotSupportedError.new("You cannot call both the `links` method and the `select` method in the same query.") if @links_navigation_property raise OData::NotSupportedError.new("You cannot call both the `count` method and the `select` method in the same query.") if @count @select |= fields expands = fields.find_all { |f| /\// =~ f } expands.each do |e| parts = e.split '/' @expands |= [parts[0...-1].join('/')] end self end
ruby
def select(*fields) raise OData::NotSupportedError.new("You cannot call both the `links` method and the `select` method in the same query.") if @links_navigation_property raise OData::NotSupportedError.new("You cannot call both the `count` method and the `select` method in the same query.") if @count @select |= fields expands = fields.find_all { |f| /\// =~ f } expands.each do |e| parts = e.split '/' @expands |= [parts[0...-1].join('/')] end self end
[ "def", "select", "(", "*", "fields", ")", "raise", "OData", "::", "NotSupportedError", ".", "new", "(", "\"You cannot call both the `links` method and the `select` method in the same query.\"", ")", "if", "@links_navigation_property", "raise", "OData", "::", "NotSupportedError", ".", "new", "(", "\"You cannot call both the `count` method and the `select` method in the same query.\"", ")", "if", "@count", "@select", "|=", "fields", "expands", "=", "fields", ".", "find_all", "{", "|", "f", "|", "/", "\\/", "/", "=~", "f", "}", "expands", ".", "each", "do", "|", "e", "|", "parts", "=", "e", ".", "split", "'/'", "@expands", "|=", "[", "parts", "[", "0", "...", "-", "1", "]", ".", "join", "(", "'/'", ")", "]", "end", "self", "end" ]
Used to customize the properties that are returned for "ad-hoc" queries @param [Array<String>] properties to return @example svc.Products.select('Price', 'Rating')
[ "Used", "to", "customize", "the", "properties", "that", "are", "returned", "for", "ad", "-", "hoc", "queries" ]
ca3d441494aa2f745c7f7fb2cd90173956f73663
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/query_builder.rb#L144-L157
22,185
jaredholdcroft/strava-api-v3
lib/strava/api/v3/common.rb
Strava::Api::V3.Common.sanitize_request_parameters
def sanitize_request_parameters(parameters) parameters.reduce({}) do |result, (key, value)| # if the parameter is an array that contains non-enumerable values, # turn it into a comma-separated list # in Ruby 1.8.7, strings are enumerable, but we don't care if value.is_a?(Array) && value.none? {|entry| entry.is_a?(Enumerable) && !entry.is_a?(String)} value = value.join(",") end value = value.to_time if value.is_a? DateTime value = value.to_i if value.is_a? Time result.merge(key => value) end end
ruby
def sanitize_request_parameters(parameters) parameters.reduce({}) do |result, (key, value)| # if the parameter is an array that contains non-enumerable values, # turn it into a comma-separated list # in Ruby 1.8.7, strings are enumerable, but we don't care if value.is_a?(Array) && value.none? {|entry| entry.is_a?(Enumerable) && !entry.is_a?(String)} value = value.join(",") end value = value.to_time if value.is_a? DateTime value = value.to_i if value.is_a? Time result.merge(key => value) end end
[ "def", "sanitize_request_parameters", "(", "parameters", ")", "parameters", ".", "reduce", "(", "{", "}", ")", "do", "|", "result", ",", "(", "key", ",", "value", ")", "|", "# if the parameter is an array that contains non-enumerable values,", "# turn it into a comma-separated list", "# in Ruby 1.8.7, strings are enumerable, but we don't care", "if", "value", ".", "is_a?", "(", "Array", ")", "&&", "value", ".", "none?", "{", "|", "entry", "|", "entry", ".", "is_a?", "(", "Enumerable", ")", "&&", "!", "entry", ".", "is_a?", "(", "String", ")", "}", "value", "=", "value", ".", "join", "(", "\",\"", ")", "end", "value", "=", "value", ".", "to_time", "if", "value", ".", "is_a?", "DateTime", "value", "=", "value", ".", "to_i", "if", "value", ".", "is_a?", "Time", "result", ".", "merge", "(", "key", "=>", "value", ")", "end", "end" ]
Sanitizes Ruby objects into Strava-compatible string values. @param parameters a hash of parameters. Returns a hash in which values that are arrays of non-enumerable values (Strings, Symbols, Numbers, etc.) are turned into comma-separated strings.
[ "Sanitizes", "Ruby", "objects", "into", "Strava", "-", "compatible", "string", "values", "." ]
13fb1411a8d999b56a3cfe3295e7af8696d8bdcf
https://github.com/jaredholdcroft/strava-api-v3/blob/13fb1411a8d999b56a3cfe3295e7af8696d8bdcf/lib/strava/api/v3/common.rb#L92-L105
22,186
jaredholdcroft/strava-api-v3
lib/strava/api/v3/activity_extras.rb
Strava::Api::V3.ActivityExtras.list_activity_photos
def list_activity_photos(id, args = {}, options = {}, &block) args['photo_sources'] = 'true' # Fetches the connections for given object. api_call("activities/#{id}/photos", args, 'get', options, &block) end
ruby
def list_activity_photos(id, args = {}, options = {}, &block) args['photo_sources'] = 'true' # Fetches the connections for given object. api_call("activities/#{id}/photos", args, 'get', options, &block) end
[ "def", "list_activity_photos", "(", "id", ",", "args", "=", "{", "}", ",", "options", "=", "{", "}", ",", "&", "block", ")", "args", "[", "'photo_sources'", "]", "=", "'true'", "# Fetches the connections for given object.", "api_call", "(", "\"activities/#{id}/photos\"", ",", "args", ",", "'get'", ",", "options", ",", "block", ")", "end" ]
Fetch list of photos from a specific activity, only if it is your activity See {https://strava.github.io/api/v3/activity_photos/} for full details @param id activity id @param args any additional arguments @param options (see #get_object) @param block post processing code block @return an array of photo objects. Both Strava and Instagram photos will be returned
[ "Fetch", "list", "of", "photos", "from", "a", "specific", "activity", "only", "if", "it", "is", "your", "activity" ]
13fb1411a8d999b56a3cfe3295e7af8696d8bdcf
https://github.com/jaredholdcroft/strava-api-v3/blob/13fb1411a8d999b56a3cfe3295e7af8696d8bdcf/lib/strava/api/v3/activity_extras.rb#L47-L51
22,187
jaredholdcroft/strava-api-v3
lib/strava/api/v3/stream.rb
Strava::Api::V3.Stream.retrieve_activity_streams
def retrieve_activity_streams(id, types, args = {}, options = {}, &block) # Fetches the connections for given object. api_call("activities/#{id}/streams/#{types}", args, 'get', options, &block) end
ruby
def retrieve_activity_streams(id, types, args = {}, options = {}, &block) # Fetches the connections for given object. api_call("activities/#{id}/streams/#{types}", args, 'get', options, &block) end
[ "def", "retrieve_activity_streams", "(", "id", ",", "types", ",", "args", "=", "{", "}", ",", "options", "=", "{", "}", ",", "&", "block", ")", "# Fetches the connections for given object.", "api_call", "(", "\"activities/#{id}/streams/#{types}\"", ",", "args", ",", "'get'", ",", "options", ",", "block", ")", "end" ]
Fetch information about a stream for a specific activity See {https://strava.github.io/api/v3/streams/#activity} for full details @param id activity id @param args any additional arguments @param options (see #get_object) @param block post processing code block @return an array of unordered stream objects
[ "Fetch", "information", "about", "a", "stream", "for", "a", "specific", "activity" ]
13fb1411a8d999b56a3cfe3295e7af8696d8bdcf
https://github.com/jaredholdcroft/strava-api-v3/blob/13fb1411a8d999b56a3cfe3295e7af8696d8bdcf/lib/strava/api/v3/stream.rb#L17-L20
22,188
jaredholdcroft/strava-api-v3
lib/strava/api/v3/stream.rb
Strava::Api::V3.Stream.retrieve_effort_streams
def retrieve_effort_streams(id, types, args = {}, options = {}, &block) # Fetches the connections for given object. api_call("segment_efforts/#{id}/streams/#{types}", args, 'get', options, &block) end
ruby
def retrieve_effort_streams(id, types, args = {}, options = {}, &block) # Fetches the connections for given object. api_call("segment_efforts/#{id}/streams/#{types}", args, 'get', options, &block) end
[ "def", "retrieve_effort_streams", "(", "id", ",", "types", ",", "args", "=", "{", "}", ",", "options", "=", "{", "}", ",", "&", "block", ")", "# Fetches the connections for given object.", "api_call", "(", "\"segment_efforts/#{id}/streams/#{types}\"", ",", "args", ",", "'get'", ",", "options", ",", "block", ")", "end" ]
Fetch information about a subset of the activity streams that correspond to that effort See {https://strava.github.io/api/v3/streams/#effort} for full details @param id effort id @param args any additional arguments @param options (see #get_object) @param block post processing code block @return an array of unordered stream objects
[ "Fetch", "information", "about", "a", "subset", "of", "the", "activity", "streams", "that", "correspond", "to", "that", "effort" ]
13fb1411a8d999b56a3cfe3295e7af8696d8bdcf
https://github.com/jaredholdcroft/strava-api-v3/blob/13fb1411a8d999b56a3cfe3295e7af8696d8bdcf/lib/strava/api/v3/stream.rb#L32-L35
22,189
jaredholdcroft/strava-api-v3
lib/strava/api/v3/stream.rb
Strava::Api::V3.Stream.retrieve_segment_streams
def retrieve_segment_streams(id, types, args = {}, options = {}, &block) # Fetches the connections for given object. api_call("segments/#{id}/streams/#{types}", args, 'get', options, &block) end
ruby
def retrieve_segment_streams(id, types, args = {}, options = {}, &block) # Fetches the connections for given object. api_call("segments/#{id}/streams/#{types}", args, 'get', options, &block) end
[ "def", "retrieve_segment_streams", "(", "id", ",", "types", ",", "args", "=", "{", "}", ",", "options", "=", "{", "}", ",", "&", "block", ")", "# Fetches the connections for given object.", "api_call", "(", "\"segments/#{id}/streams/#{types}\"", ",", "args", ",", "'get'", ",", "options", ",", "block", ")", "end" ]
Fetch information about a stream for a specific segment See {https://strava.github.io/api/v3/streams/#segment} for full details @param id segment id @param args any additional arguments @param options (see #get_object) @param block post processing code block @return an array of unordered stream objects
[ "Fetch", "information", "about", "a", "stream", "for", "a", "specific", "segment" ]
13fb1411a8d999b56a3cfe3295e7af8696d8bdcf
https://github.com/jaredholdcroft/strava-api-v3/blob/13fb1411a8d999b56a3cfe3295e7af8696d8bdcf/lib/strava/api/v3/stream.rb#L62-L65
22,190
ckruse/CFPropertyList
lib/cfpropertylist/rbCFTypes.rb
CFPropertyList.CFDate.set_value
def set_value(value,format=CFDate::TIMESTAMP_UNIX) if(format == CFDate::TIMESTAMP_UNIX) then @value = Time.at(value) else @value = Time.at(value + CFDate::DATE_DIFF_APPLE_UNIX) end end
ruby
def set_value(value,format=CFDate::TIMESTAMP_UNIX) if(format == CFDate::TIMESTAMP_UNIX) then @value = Time.at(value) else @value = Time.at(value + CFDate::DATE_DIFF_APPLE_UNIX) end end
[ "def", "set_value", "(", "value", ",", "format", "=", "CFDate", "::", "TIMESTAMP_UNIX", ")", "if", "(", "format", "==", "CFDate", "::", "TIMESTAMP_UNIX", ")", "then", "@value", "=", "Time", ".", "at", "(", "value", ")", "else", "@value", "=", "Time", ".", "at", "(", "value", "+", "CFDate", "::", "DATE_DIFF_APPLE_UNIX", ")", "end", "end" ]
set value to defined state set value with timestamp, either Apple or UNIX
[ "set", "value", "to", "defined", "state", "set", "value", "with", "timestamp", "either", "Apple", "or", "UNIX" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbCFTypes.rb#L176-L182
22,191
ckruse/CFPropertyList
lib/cfpropertylist/rbCFTypes.rb
CFPropertyList.CFDate.get_value
def get_value(format=CFDate::TIMESTAMP_UNIX) if(format == CFDate::TIMESTAMP_UNIX) then @value.to_i else @value.to_f - CFDate::DATE_DIFF_APPLE_UNIX end end
ruby
def get_value(format=CFDate::TIMESTAMP_UNIX) if(format == CFDate::TIMESTAMP_UNIX) then @value.to_i else @value.to_f - CFDate::DATE_DIFF_APPLE_UNIX end end
[ "def", "get_value", "(", "format", "=", "CFDate", "::", "TIMESTAMP_UNIX", ")", "if", "(", "format", "==", "CFDate", "::", "TIMESTAMP_UNIX", ")", "then", "@value", ".", "to_i", "else", "@value", ".", "to_f", "-", "CFDate", "::", "DATE_DIFF_APPLE_UNIX", "end", "end" ]
get timestamp, either UNIX or Apple timestamp
[ "get", "timestamp", "either", "UNIX", "or", "Apple", "timestamp" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbCFTypes.rb#L185-L191
22,192
ckruse/CFPropertyList
lib/cfpropertylist/rbCFTypes.rb
CFPropertyList.CFArray.to_xml
def to_xml(parser) n = parser.new_node('array') @value.each do |v| n = parser.append_node(n, v.to_xml(parser)) end n end
ruby
def to_xml(parser) n = parser.new_node('array') @value.each do |v| n = parser.append_node(n, v.to_xml(parser)) end n end
[ "def", "to_xml", "(", "parser", ")", "n", "=", "parser", ".", "new_node", "(", "'array'", ")", "@value", ".", "each", "do", "|", "v", "|", "n", "=", "parser", ".", "append_node", "(", "n", ",", "v", ".", "to_xml", "(", "parser", ")", ")", "end", "n", "end" ]
create a new array CFType convert to XML
[ "create", "a", "new", "array", "CFType", "convert", "to", "XML" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbCFTypes.rb#L278-L284
22,193
ckruse/CFPropertyList
lib/cfpropertylist/rbCFTypes.rb
CFPropertyList.CFDictionary.to_xml
def to_xml(parser) n = parser.new_node('dict') @value.each_pair do |key, value| k = parser.append_node(parser.new_node('key'), parser.new_text(key.to_s)) n = parser.append_node(n, k) n = parser.append_node(n, value.to_xml(parser)) end n end
ruby
def to_xml(parser) n = parser.new_node('dict') @value.each_pair do |key, value| k = parser.append_node(parser.new_node('key'), parser.new_text(key.to_s)) n = parser.append_node(n, k) n = parser.append_node(n, value.to_xml(parser)) end n end
[ "def", "to_xml", "(", "parser", ")", "n", "=", "parser", ".", "new_node", "(", "'dict'", ")", "@value", ".", "each_pair", "do", "|", "key", ",", "value", "|", "k", "=", "parser", ".", "append_node", "(", "parser", ".", "new_node", "(", "'key'", ")", ",", "parser", ".", "new_text", "(", "key", ".", "to_s", ")", ")", "n", "=", "parser", ".", "append_node", "(", "n", ",", "k", ")", "n", "=", "parser", ".", "append_node", "(", "n", ",", "value", ".", "to_xml", "(", "parser", ")", ")", "end", "n", "end" ]
Create new CFDictonary type. convert to XML
[ "Create", "new", "CFDictonary", "type", ".", "convert", "to", "XML" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbCFTypes.rb#L305-L313
22,194
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.load
def load(opts) @unique_table = {} @count_objects = 0 @object_refs = 0 @written_object_count = 0 @object_table = [] @object_ref_size = 0 @offsets = [] fd = nil if(opts.has_key?(:file)) fd = File.open(opts[:file],"rb") file = opts[:file] else fd = StringIO.new(opts[:data],"rb") file = "<string>" end # first, we read the trailer: 32 byte from the end fd.seek(-32,IO::SEEK_END) buff = fd.read(32) offset_size, object_ref_size, number_of_objects, top_object, table_offset = buff.unpack "x6CCx4Nx4Nx4N" # after that, get the offset table fd.seek(table_offset, IO::SEEK_SET) coded_offset_table = fd.read(number_of_objects * offset_size) raise CFFormatError.new("#{file}: Format error!") unless coded_offset_table.bytesize == number_of_objects * offset_size @count_objects = number_of_objects # decode offset table if(offset_size != 3) formats = ["","C*","n*","","N*"] @offsets = coded_offset_table.unpack(formats[offset_size]) else @offsets = coded_offset_table.unpack("C*").each_slice(3).map { |x,y,z| (x << 16) | (y << 8) | z } end @object_ref_size = object_ref_size val = read_binary_object_at(file,fd,top_object) fd.close val end
ruby
def load(opts) @unique_table = {} @count_objects = 0 @object_refs = 0 @written_object_count = 0 @object_table = [] @object_ref_size = 0 @offsets = [] fd = nil if(opts.has_key?(:file)) fd = File.open(opts[:file],"rb") file = opts[:file] else fd = StringIO.new(opts[:data],"rb") file = "<string>" end # first, we read the trailer: 32 byte from the end fd.seek(-32,IO::SEEK_END) buff = fd.read(32) offset_size, object_ref_size, number_of_objects, top_object, table_offset = buff.unpack "x6CCx4Nx4Nx4N" # after that, get the offset table fd.seek(table_offset, IO::SEEK_SET) coded_offset_table = fd.read(number_of_objects * offset_size) raise CFFormatError.new("#{file}: Format error!") unless coded_offset_table.bytesize == number_of_objects * offset_size @count_objects = number_of_objects # decode offset table if(offset_size != 3) formats = ["","C*","n*","","N*"] @offsets = coded_offset_table.unpack(formats[offset_size]) else @offsets = coded_offset_table.unpack("C*").each_slice(3).map { |x,y,z| (x << 16) | (y << 8) | z } end @object_ref_size = object_ref_size val = read_binary_object_at(file,fd,top_object) fd.close val end
[ "def", "load", "(", "opts", ")", "@unique_table", "=", "{", "}", "@count_objects", "=", "0", "@object_refs", "=", "0", "@written_object_count", "=", "0", "@object_table", "=", "[", "]", "@object_ref_size", "=", "0", "@offsets", "=", "[", "]", "fd", "=", "nil", "if", "(", "opts", ".", "has_key?", "(", ":file", ")", ")", "fd", "=", "File", ".", "open", "(", "opts", "[", ":file", "]", ",", "\"rb\"", ")", "file", "=", "opts", "[", ":file", "]", "else", "fd", "=", "StringIO", ".", "new", "(", "opts", "[", ":data", "]", ",", "\"rb\"", ")", "file", "=", "\"<string>\"", "end", "# first, we read the trailer: 32 byte from the end", "fd", ".", "seek", "(", "-", "32", ",", "IO", "::", "SEEK_END", ")", "buff", "=", "fd", ".", "read", "(", "32", ")", "offset_size", ",", "object_ref_size", ",", "number_of_objects", ",", "top_object", ",", "table_offset", "=", "buff", ".", "unpack", "\"x6CCx4Nx4Nx4N\"", "# after that, get the offset table", "fd", ".", "seek", "(", "table_offset", ",", "IO", "::", "SEEK_SET", ")", "coded_offset_table", "=", "fd", ".", "read", "(", "number_of_objects", "*", "offset_size", ")", "raise", "CFFormatError", ".", "new", "(", "\"#{file}: Format error!\"", ")", "unless", "coded_offset_table", ".", "bytesize", "==", "number_of_objects", "*", "offset_size", "@count_objects", "=", "number_of_objects", "# decode offset table", "if", "(", "offset_size", "!=", "3", ")", "formats", "=", "[", "\"\"", ",", "\"C*\"", ",", "\"n*\"", ",", "\"\"", ",", "\"N*\"", "]", "@offsets", "=", "coded_offset_table", ".", "unpack", "(", "formats", "[", "offset_size", "]", ")", "else", "@offsets", "=", "coded_offset_table", ".", "unpack", "(", "\"C*\"", ")", ".", "each_slice", "(", "3", ")", ".", "map", "{", "|", "x", ",", "y", ",", "z", "|", "(", "x", "<<", "16", ")", "|", "(", "y", "<<", "8", ")", "|", "z", "}", "end", "@object_ref_size", "=", "object_ref_size", "val", "=", "read_binary_object_at", "(", "file", ",", "fd", ",", "top_object", ")", "fd", ".", "close", "val", "end" ]
Read a binary plist file
[ "Read", "a", "binary", "plist", "file" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L9-L57
22,195
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.to_str
def to_str(opts={}) @unique_table = {} @count_objects = 0 @object_refs = 0 @written_object_count = 0 @object_table = [] @offsets = [] binary_str = "bplist00" @object_refs = count_object_refs(opts[:root]) opts[:root].to_binary(self) next_offset = 8 offsets = @object_table.map do |object| offset = next_offset next_offset += object.bytesize offset end binary_str << @object_table.join table_offset = next_offset offset_size = Binary.bytes_needed(table_offset) if offset_size < 8 # Fast path: encode the entire offset array at once. binary_str << offsets.pack((%w(C n N N)[offset_size - 1]) + '*') else # Slow path: host may be little or big endian, must pack each offset # separately. offsets.each do |offset| binary_str << "#{Binary.pack_it_with_size(offset_size,offset)}" end end binary_str << [offset_size, object_ref_size(@object_refs)].pack("x6CC") binary_str << [@object_table.size].pack("x4N") binary_str << [0].pack("x4N") binary_str << [table_offset].pack("x4N") binary_str end
ruby
def to_str(opts={}) @unique_table = {} @count_objects = 0 @object_refs = 0 @written_object_count = 0 @object_table = [] @offsets = [] binary_str = "bplist00" @object_refs = count_object_refs(opts[:root]) opts[:root].to_binary(self) next_offset = 8 offsets = @object_table.map do |object| offset = next_offset next_offset += object.bytesize offset end binary_str << @object_table.join table_offset = next_offset offset_size = Binary.bytes_needed(table_offset) if offset_size < 8 # Fast path: encode the entire offset array at once. binary_str << offsets.pack((%w(C n N N)[offset_size - 1]) + '*') else # Slow path: host may be little or big endian, must pack each offset # separately. offsets.each do |offset| binary_str << "#{Binary.pack_it_with_size(offset_size,offset)}" end end binary_str << [offset_size, object_ref_size(@object_refs)].pack("x6CC") binary_str << [@object_table.size].pack("x4N") binary_str << [0].pack("x4N") binary_str << [table_offset].pack("x4N") binary_str end
[ "def", "to_str", "(", "opts", "=", "{", "}", ")", "@unique_table", "=", "{", "}", "@count_objects", "=", "0", "@object_refs", "=", "0", "@written_object_count", "=", "0", "@object_table", "=", "[", "]", "@offsets", "=", "[", "]", "binary_str", "=", "\"bplist00\"", "@object_refs", "=", "count_object_refs", "(", "opts", "[", ":root", "]", ")", "opts", "[", ":root", "]", ".", "to_binary", "(", "self", ")", "next_offset", "=", "8", "offsets", "=", "@object_table", ".", "map", "do", "|", "object", "|", "offset", "=", "next_offset", "next_offset", "+=", "object", ".", "bytesize", "offset", "end", "binary_str", "<<", "@object_table", ".", "join", "table_offset", "=", "next_offset", "offset_size", "=", "Binary", ".", "bytes_needed", "(", "table_offset", ")", "if", "offset_size", "<", "8", "# Fast path: encode the entire offset array at once.", "binary_str", "<<", "offsets", ".", "pack", "(", "(", "%w(", "C", "n", "N", "N", ")", "[", "offset_size", "-", "1", "]", ")", "+", "'*'", ")", "else", "# Slow path: host may be little or big endian, must pack each offset", "# separately.", "offsets", ".", "each", "do", "|", "offset", "|", "binary_str", "<<", "\"#{Binary.pack_it_with_size(offset_size,offset)}\"", "end", "end", "binary_str", "<<", "[", "offset_size", ",", "object_ref_size", "(", "@object_refs", ")", "]", ".", "pack", "(", "\"x6CC\"", ")", "binary_str", "<<", "[", "@object_table", ".", "size", "]", ".", "pack", "(", "\"x4N\"", ")", "binary_str", "<<", "[", "0", "]", ".", "pack", "(", "\"x4N\"", ")", "binary_str", "<<", "[", "table_offset", "]", ".", "pack", "(", "\"x4N\"", ")", "binary_str", "end" ]
Convert CFPropertyList to binary format; since we have to count our objects we simply unique CFDictionary and CFArray
[ "Convert", "CFPropertyList", "to", "binary", "format", ";", "since", "we", "have", "to", "count", "our", "objects", "we", "simply", "unique", "CFDictionary", "and", "CFArray" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L61-L105
22,196
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.read_binary_int
def read_binary_int(fname,fd,length) if length > 4 raise CFFormatError.new("Integer greater than 16 bytes: #{length}") end nbytes = 1 << length buff = fd.read(nbytes) CFInteger.new( case length when 0 then buff.unpack("C")[0] when 1 then buff.unpack("n")[0] when 2 then buff.unpack("N")[0] # 8 byte integers are always signed when 3 then buff.unpack("q>")[0] # 16 byte integers are used to represent unsigned 8 byte integers # where the unsigned value is stored in the lower 8 bytes and the # upper 8 bytes are unused. when 4 then buff.unpack("Q>Q>")[1] end ) end
ruby
def read_binary_int(fname,fd,length) if length > 4 raise CFFormatError.new("Integer greater than 16 bytes: #{length}") end nbytes = 1 << length buff = fd.read(nbytes) CFInteger.new( case length when 0 then buff.unpack("C")[0] when 1 then buff.unpack("n")[0] when 2 then buff.unpack("N")[0] # 8 byte integers are always signed when 3 then buff.unpack("q>")[0] # 16 byte integers are used to represent unsigned 8 byte integers # where the unsigned value is stored in the lower 8 bytes and the # upper 8 bytes are unused. when 4 then buff.unpack("Q>Q>")[1] end ) end
[ "def", "read_binary_int", "(", "fname", ",", "fd", ",", "length", ")", "if", "length", ">", "4", "raise", "CFFormatError", ".", "new", "(", "\"Integer greater than 16 bytes: #{length}\"", ")", "end", "nbytes", "=", "1", "<<", "length", "buff", "=", "fd", ".", "read", "(", "nbytes", ")", "CFInteger", ".", "new", "(", "case", "length", "when", "0", "then", "buff", ".", "unpack", "(", "\"C\"", ")", "[", "0", "]", "when", "1", "then", "buff", ".", "unpack", "(", "\"n\"", ")", "[", "0", "]", "when", "2", "then", "buff", ".", "unpack", "(", "\"N\"", ")", "[", "0", "]", "# 8 byte integers are always signed", "when", "3", "then", "buff", ".", "unpack", "(", "\"q>\"", ")", "[", "0", "]", "# 16 byte integers are used to represent unsigned 8 byte integers", "# where the unsigned value is stored in the lower 8 bytes and the", "# upper 8 bytes are unused.", "when", "4", "then", "buff", ".", "unpack", "(", "\"Q>Q>\"", ")", "[", "1", "]", "end", ")", "end" ]
read a binary int value
[ "read", "a", "binary", "int", "value" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L125-L147
22,197
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.read_binary_real
def read_binary_real(fname,fd,length) raise CFFormatError.new("Real greater than 8 bytes: #{length}") if length > 3 nbytes = 1 << length buff = fd.read(nbytes) CFReal.new( case length when 0 # 1 byte float? must be an error raise CFFormatError.new("got #{length+1} byte float, must be an error!") when 1 # 2 byte float? must be an error raise CFFormatError.new("got #{length+1} byte float, must be an error!") when 2 then buff.reverse.unpack("e")[0] when 3 then buff.reverse.unpack("E")[0] else fail "unexpected length: #{length}" end ) end
ruby
def read_binary_real(fname,fd,length) raise CFFormatError.new("Real greater than 8 bytes: #{length}") if length > 3 nbytes = 1 << length buff = fd.read(nbytes) CFReal.new( case length when 0 # 1 byte float? must be an error raise CFFormatError.new("got #{length+1} byte float, must be an error!") when 1 # 2 byte float? must be an error raise CFFormatError.new("got #{length+1} byte float, must be an error!") when 2 then buff.reverse.unpack("e")[0] when 3 then buff.reverse.unpack("E")[0] else fail "unexpected length: #{length}" end ) end
[ "def", "read_binary_real", "(", "fname", ",", "fd", ",", "length", ")", "raise", "CFFormatError", ".", "new", "(", "\"Real greater than 8 bytes: #{length}\"", ")", "if", "length", ">", "3", "nbytes", "=", "1", "<<", "length", "buff", "=", "fd", ".", "read", "(", "nbytes", ")", "CFReal", ".", "new", "(", "case", "length", "when", "0", "# 1 byte float? must be an error", "raise", "CFFormatError", ".", "new", "(", "\"got #{length+1} byte float, must be an error!\"", ")", "when", "1", "# 2 byte float? must be an error", "raise", "CFFormatError", ".", "new", "(", "\"got #{length+1} byte float, must be an error!\"", ")", "when", "2", "then", "buff", ".", "reverse", ".", "unpack", "(", "\"e\"", ")", "[", "0", "]", "when", "3", "then", "buff", ".", "reverse", ".", "unpack", "(", "\"E\"", ")", "[", "0", "]", "else", "fail", "\"unexpected length: #{length}\"", "end", ")", "end" ]
read a binary real value
[ "read", "a", "binary", "real", "value" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L151-L171
22,198
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.read_binary_date
def read_binary_date(fname,fd,length) raise CFFormatError.new("Date greater than 8 bytes: #{length}") if length > 3 nbytes = 1 << length buff = fd.read(nbytes) CFDate.new( case length when 0 then # 1 byte CFDate is an error raise CFFormatError.new("#{length+1} byte CFDate, error") when 1 then # 2 byte CFDate is an error raise CFFormatError.new("#{length+1} byte CFDate, error") when 2 then buff.reverse.unpack("e")[0] when 3 then buff.reverse.unpack("E")[0] end, CFDate::TIMESTAMP_APPLE ) end
ruby
def read_binary_date(fname,fd,length) raise CFFormatError.new("Date greater than 8 bytes: #{length}") if length > 3 nbytes = 1 << length buff = fd.read(nbytes) CFDate.new( case length when 0 then # 1 byte CFDate is an error raise CFFormatError.new("#{length+1} byte CFDate, error") when 1 then # 2 byte CFDate is an error raise CFFormatError.new("#{length+1} byte CFDate, error") when 2 then buff.reverse.unpack("e")[0] when 3 then buff.reverse.unpack("E")[0] end, CFDate::TIMESTAMP_APPLE ) end
[ "def", "read_binary_date", "(", "fname", ",", "fd", ",", "length", ")", "raise", "CFFormatError", ".", "new", "(", "\"Date greater than 8 bytes: #{length}\"", ")", "if", "length", ">", "3", "nbytes", "=", "1", "<<", "length", "buff", "=", "fd", ".", "read", "(", "nbytes", ")", "CFDate", ".", "new", "(", "case", "length", "when", "0", "then", "# 1 byte CFDate is an error", "raise", "CFFormatError", ".", "new", "(", "\"#{length+1} byte CFDate, error\"", ")", "when", "1", "then", "# 2 byte CFDate is an error", "raise", "CFFormatError", ".", "new", "(", "\"#{length+1} byte CFDate, error\"", ")", "when", "2", "then", "buff", ".", "reverse", ".", "unpack", "(", "\"e\"", ")", "[", "0", "]", "when", "3", "then", "buff", ".", "reverse", ".", "unpack", "(", "\"E\"", ")", "[", "0", "]", "end", ",", "CFDate", "::", "TIMESTAMP_APPLE", ")", "end" ]
read a binary date value
[ "read", "a", "binary", "date", "value" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L175-L194
22,199
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.read_binary_data
def read_binary_data(fname,fd,length) CFData.new(read_fd(fd, length), CFData::DATA_RAW) end
ruby
def read_binary_data(fname,fd,length) CFData.new(read_fd(fd, length), CFData::DATA_RAW) end
[ "def", "read_binary_data", "(", "fname", ",", "fd", ",", "length", ")", "CFData", ".", "new", "(", "read_fd", "(", "fd", ",", "length", ")", ",", "CFData", "::", "DATA_RAW", ")", "end" ]
Read a binary data value
[ "Read", "a", "binary", "data", "value" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L198-L200