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
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
state-machines/state_machines
lib/state_machines/event.rb
StateMachines.Event.fire
def fire(object, *args) machine.reset(object) if transition = transition_for(object) transition.perform(*args) else on_failure(object, *args) false end end
ruby
def fire(object, *args) machine.reset(object) if transition = transition_for(object) transition.perform(*args) else on_failure(object, *args) false end end
[ "def", "fire", "(", "object", ",", "*", "args", ")", "machine", ".", "reset", "(", "object", ")", "if", "transition", "=", "transition_for", "(", "object", ")", "transition", ".", "perform", "(", "args", ")", "else", "on_failure", "(", "object", ",", "args", ")", "false", "end", "end" ]
Attempts to perform the next available transition on the given object. If no transitions can be made, then this will return false, otherwise true. Any additional arguments are passed to the StateMachines::Transition#perform instance method.
[ "Attempts", "to", "perform", "the", "next", "available", "transition", "on", "the", "given", "object", ".", "If", "no", "transitions", "can", "be", "made", "then", "this", "will", "return", "false", "otherwise", "true", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/event.rb#L151-L160
train
state-machines/state_machines
lib/state_machines/event.rb
StateMachines.Event.on_failure
def on_failure(object, *args) state = machine.states.match!(object) machine.invalidate(object, :state, :invalid_transition, [[:event, human_name(object.class)], [:state, state.human_name(object.class)]]) transition = Transition.new(object, machine, name, state.name, state.name) transition.args = args if args.any? transition.run_callbacks(:before => false) end
ruby
def on_failure(object, *args) state = machine.states.match!(object) machine.invalidate(object, :state, :invalid_transition, [[:event, human_name(object.class)], [:state, state.human_name(object.class)]]) transition = Transition.new(object, machine, name, state.name, state.name) transition.args = args if args.any? transition.run_callbacks(:before => false) end
[ "def", "on_failure", "(", "object", ",", "*", "args", ")", "state", "=", "machine", ".", "states", ".", "match!", "(", "object", ")", "machine", ".", "invalidate", "(", "object", ",", ":state", ",", ":invalid_transition", ",", "[", "[", ":event", ",", "human_name", "(", "object", ".", "class", ")", "]", ",", "[", ":state", ",", "state", ".", "human_name", "(", "object", ".", "class", ")", "]", "]", ")", "transition", "=", "Transition", ".", "new", "(", "object", ",", "machine", ",", "name", ",", "state", ".", "name", ",", "state", ".", "name", ")", "transition", ".", "args", "=", "args", "if", "args", ".", "any?", "transition", ".", "run_callbacks", "(", ":before", "=>", "false", ")", "end" ]
Marks the object as invalid and runs any failure callbacks associated with this event. This should get called anytime this event fails to transition.
[ "Marks", "the", "object", "as", "invalid", "and", "runs", "any", "failure", "callbacks", "associated", "with", "this", "event", ".", "This", "should", "get", "called", "anytime", "this", "event", "fails", "to", "transition", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/event.rb#L164-L171
train
state-machines/state_machines
lib/state_machines/event.rb
StateMachines.Event.add_actions
def add_actions # Checks whether the event can be fired on the current object machine.define_helper(:instance, "can_#{qualified_name}?") do |machine, object, *args| machine.event(name).can_fire?(object, *args) end # Gets the next transition that would be performed if the event were # fired now machine.define_helper(:instance, "#{qualified_name}_transition") do |machine, object, *args| machine.event(name).transition_for(object, *args) end # Fires the event machine.define_helper(:instance, qualified_name) do |machine, object, *args| machine.event(name).fire(object, *args) end # Fires the event, raising an exception if it fails machine.define_helper(:instance, "#{qualified_name}!") do |machine, object, *args| object.send(qualified_name, *args) || raise(StateMachines::InvalidTransition.new(object, machine, name)) end end
ruby
def add_actions # Checks whether the event can be fired on the current object machine.define_helper(:instance, "can_#{qualified_name}?") do |machine, object, *args| machine.event(name).can_fire?(object, *args) end # Gets the next transition that would be performed if the event were # fired now machine.define_helper(:instance, "#{qualified_name}_transition") do |machine, object, *args| machine.event(name).transition_for(object, *args) end # Fires the event machine.define_helper(:instance, qualified_name) do |machine, object, *args| machine.event(name).fire(object, *args) end # Fires the event, raising an exception if it fails machine.define_helper(:instance, "#{qualified_name}!") do |machine, object, *args| object.send(qualified_name, *args) || raise(StateMachines::InvalidTransition.new(object, machine, name)) end end
[ "def", "add_actions", "# Checks whether the event can be fired on the current object", "machine", ".", "define_helper", "(", ":instance", ",", "\"can_#{qualified_name}?\"", ")", "do", "|", "machine", ",", "object", ",", "*", "args", "|", "machine", ".", "event", "(", "name", ")", ".", "can_fire?", "(", "object", ",", "args", ")", "end", "# Gets the next transition that would be performed if the event were", "# fired now", "machine", ".", "define_helper", "(", ":instance", ",", "\"#{qualified_name}_transition\"", ")", "do", "|", "machine", ",", "object", ",", "*", "args", "|", "machine", ".", "event", "(", "name", ")", ".", "transition_for", "(", "object", ",", "args", ")", "end", "# Fires the event", "machine", ".", "define_helper", "(", ":instance", ",", "qualified_name", ")", "do", "|", "machine", ",", "object", ",", "*", "args", "|", "machine", ".", "event", "(", "name", ")", ".", "fire", "(", "object", ",", "args", ")", "end", "# Fires the event, raising an exception if it fails", "machine", ".", "define_helper", "(", ":instance", ",", "\"#{qualified_name}!\"", ")", "do", "|", "machine", ",", "object", ",", "*", "args", "|", "object", ".", "send", "(", "qualified_name", ",", "args", ")", "||", "raise", "(", "StateMachines", "::", "InvalidTransition", ".", "new", "(", "object", ",", "machine", ",", "name", ")", ")", "end", "end" ]
Add the various instance methods that can transition the object using the current event
[ "Add", "the", "various", "instance", "methods", "that", "can", "transition", "the", "object", "using", "the", "current", "event" ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/event.rb#L207-L228
train
state-machines/state_machines
lib/state_machines/machine_collection.rb
StateMachines.MachineCollection.transitions
def transitions(object, action, options = {}) transitions = map do |name, machine| machine.events.attribute_transition_for(object, true) if machine.action == action end AttributeTransitionCollection.new(transitions.compact, {use_transactions: resolve_use_transactions}.merge(options)) end
ruby
def transitions(object, action, options = {}) transitions = map do |name, machine| machine.events.attribute_transition_for(object, true) if machine.action == action end AttributeTransitionCollection.new(transitions.compact, {use_transactions: resolve_use_transactions}.merge(options)) end
[ "def", "transitions", "(", "object", ",", "action", ",", "options", "=", "{", "}", ")", "transitions", "=", "map", "do", "|", "name", ",", "machine", "|", "machine", ".", "events", ".", "attribute_transition_for", "(", "object", ",", "true", ")", "if", "machine", ".", "action", "==", "action", "end", "AttributeTransitionCollection", ".", "new", "(", "transitions", ".", "compact", ",", "{", "use_transactions", ":", "resolve_use_transactions", "}", ".", "merge", "(", "options", ")", ")", "end" ]
Builds the collection of transitions for all event attributes defined on the given object. This will only include events whose machine actions match the one specified. These should only be fired as a result of the action being run.
[ "Builds", "the", "collection", "of", "transitions", "for", "all", "event", "attributes", "defined", "on", "the", "given", "object", ".", "This", "will", "only", "include", "events", "whose", "machine", "actions", "match", "the", "one", "specified", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine_collection.rb#L76-L82
train
state-machines/state_machines
lib/state_machines/node_collection.rb
StateMachines.NodeCollection.<<
def <<(node) @nodes << node @index_names.each { |name| add_to_index(name, value(node, name), node) } @contexts.each { |context| eval_context(context, node) } self end
ruby
def <<(node) @nodes << node @index_names.each { |name| add_to_index(name, value(node, name), node) } @contexts.each { |context| eval_context(context, node) } self end
[ "def", "<<", "(", "node", ")", "@nodes", "<<", "node", "@index_names", ".", "each", "{", "|", "name", "|", "add_to_index", "(", "name", ",", "value", "(", "node", ",", "name", ")", ",", "node", ")", "}", "@contexts", ".", "each", "{", "|", "context", "|", "eval_context", "(", "context", ",", "node", ")", "}", "self", "end" ]
Adds a new node to the collection. By doing so, this will also add it to the configured indices. This will also evaluate any existings contexts that match the new node.
[ "Adds", "a", "new", "node", "to", "the", "collection", ".", "By", "doing", "so", "this", "will", "also", "add", "it", "to", "the", "configured", "indices", ".", "This", "will", "also", "evaluate", "any", "existings", "contexts", "that", "match", "the", "new", "node", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/node_collection.rb#L85-L90
train
state-machines/state_machines
lib/state_machines/node_collection.rb
StateMachines.NodeCollection.update_index
def update_index(name, node) index = self.index(name) old_key = index.key(node) new_key = value(node, name) # Only replace the key if it's changed if old_key != new_key remove_from_index(name, old_key) add_to_index(name, new_key, node) end end
ruby
def update_index(name, node) index = self.index(name) old_key = index.key(node) new_key = value(node, name) # Only replace the key if it's changed if old_key != new_key remove_from_index(name, old_key) add_to_index(name, new_key, node) end end
[ "def", "update_index", "(", "name", ",", "node", ")", "index", "=", "self", ".", "index", "(", "name", ")", "old_key", "=", "index", ".", "key", "(", "node", ")", "new_key", "=", "value", "(", "node", ",", "name", ")", "# Only replace the key if it's changed", "if", "old_key", "!=", "new_key", "remove_from_index", "(", "name", ",", "old_key", ")", "add_to_index", "(", "name", ",", "new_key", ",", "node", ")", "end", "end" ]
Updates the node for the given index, including the string and symbol versions of the index
[ "Updates", "the", "node", "for", "the", "given", "index", "including", "the", "string", "and", "symbol", "versions", "of", "the", "index" ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/node_collection.rb#L196-L206
train
state-machines/state_machines
lib/state_machines/node_collection.rb
StateMachines.NodeCollection.eval_context
def eval_context(context, node) node.context(&context[:block]) if context[:nodes].matches?(node.name) end
ruby
def eval_context(context, node) node.context(&context[:block]) if context[:nodes].matches?(node.name) end
[ "def", "eval_context", "(", "context", ",", "node", ")", "node", ".", "context", "(", "context", "[", ":block", "]", ")", "if", "context", "[", ":nodes", "]", ".", "matches?", "(", "node", ".", "name", ")", "end" ]
Evaluates the given context for a particular node. This will only evaluate the context if the node matches.
[ "Evaluates", "the", "given", "context", "for", "a", "particular", "node", ".", "This", "will", "only", "evaluate", "the", "context", "if", "the", "node", "matches", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/node_collection.rb#L215-L217
train
state-machines/state_machines
lib/state_machines/transition.rb
StateMachines.Transition.pause
def pause raise ArgumentError, 'around_transition callbacks cannot be called in multiple execution contexts in java implementations of Ruby. Use before/after_transitions instead.' unless self.class.pause_supported? unless @resume_block require 'continuation' unless defined?(callcc) callcc do |block| @paused_block = block throw :halt, true end end end
ruby
def pause raise ArgumentError, 'around_transition callbacks cannot be called in multiple execution contexts in java implementations of Ruby. Use before/after_transitions instead.' unless self.class.pause_supported? unless @resume_block require 'continuation' unless defined?(callcc) callcc do |block| @paused_block = block throw :halt, true end end end
[ "def", "pause", "raise", "ArgumentError", ",", "'around_transition callbacks cannot be called in multiple execution contexts in java implementations of Ruby. Use before/after_transitions instead.'", "unless", "self", ".", "class", ".", "pause_supported?", "unless", "@resume_block", "require", "'continuation'", "unless", "defined?", "(", "callcc", ")", "callcc", "do", "|", "block", "|", "@paused_block", "=", "block", "throw", ":halt", ",", "true", "end", "end", "end" ]
Pauses the current callback execution. This should only occur within around callbacks when the remainder of the callback will be executed at a later point in time.
[ "Pauses", "the", "current", "callback", "execution", ".", "This", "should", "only", "occur", "within", "around", "callbacks", "when", "the", "remainder", "of", "the", "callback", "will", "be", "executed", "at", "a", "later", "point", "in", "time", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition.rb#L307-L317
train
state-machines/state_machines
lib/state_machines/transition.rb
StateMachines.Transition.resume
def resume if @paused_block halted, error = callcc do |block| @resume_block = block @paused_block.call end @resume_block = @paused_block = nil raise error if error !halted else true end end
ruby
def resume if @paused_block halted, error = callcc do |block| @resume_block = block @paused_block.call end @resume_block = @paused_block = nil raise error if error !halted else true end end
[ "def", "resume", "if", "@paused_block", "halted", ",", "error", "=", "callcc", "do", "|", "block", "|", "@resume_block", "=", "block", "@paused_block", ".", "call", "end", "@resume_block", "=", "@paused_block", "=", "nil", "raise", "error", "if", "error", "!", "halted", "else", "true", "end", "end" ]
Resumes the execution of a previously paused callback execution. Once the paused callbacks complete, the current execution will continue.
[ "Resumes", "the", "execution", "of", "a", "previously", "paused", "callback", "execution", ".", "Once", "the", "paused", "callbacks", "complete", "the", "current", "execution", "will", "continue", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition.rb#L321-L335
train
state-machines/state_machines
lib/state_machines/transition.rb
StateMachines.Transition.before
def before(complete = true, index = 0, &block) unless @before_run while callback = machine.callbacks[:before][index] index += 1 if callback.type == :around # Around callback: need to handle recursively. Execution only gets # paused if: # * The block fails and the callback doesn't run on failures OR # * The block succeeds, but after callbacks are disabled (in which # case a continuation is stored for later execution) return if catch(:cancel) do callback.call(object, context, self) do before(complete, index, &block) pause if @success && !complete throw :cancel, true unless @success end end else # Normal before callback callback.call(object, context, self) end end @before_run = true end action = {:success => true}.merge(block_given? ? yield : {}) @result, @success = action[:result], action[:success] end
ruby
def before(complete = true, index = 0, &block) unless @before_run while callback = machine.callbacks[:before][index] index += 1 if callback.type == :around # Around callback: need to handle recursively. Execution only gets # paused if: # * The block fails and the callback doesn't run on failures OR # * The block succeeds, but after callbacks are disabled (in which # case a continuation is stored for later execution) return if catch(:cancel) do callback.call(object, context, self) do before(complete, index, &block) pause if @success && !complete throw :cancel, true unless @success end end else # Normal before callback callback.call(object, context, self) end end @before_run = true end action = {:success => true}.merge(block_given? ? yield : {}) @result, @success = action[:result], action[:success] end
[ "def", "before", "(", "complete", "=", "true", ",", "index", "=", "0", ",", "&", "block", ")", "unless", "@before_run", "while", "callback", "=", "machine", ".", "callbacks", "[", ":before", "]", "[", "index", "]", "index", "+=", "1", "if", "callback", ".", "type", "==", ":around", "# Around callback: need to handle recursively. Execution only gets", "# paused if:", "# * The block fails and the callback doesn't run on failures OR", "# * The block succeeds, but after callbacks are disabled (in which", "# case a continuation is stored for later execution)", "return", "if", "catch", "(", ":cancel", ")", "do", "callback", ".", "call", "(", "object", ",", "context", ",", "self", ")", "do", "before", "(", "complete", ",", "index", ",", "block", ")", "pause", "if", "@success", "&&", "!", "complete", "throw", ":cancel", ",", "true", "unless", "@success", "end", "end", "else", "# Normal before callback", "callback", ".", "call", "(", "object", ",", "context", ",", "self", ")", "end", "end", "@before_run", "=", "true", "end", "action", "=", "{", ":success", "=>", "true", "}", ".", "merge", "(", "block_given?", "?", "yield", ":", "{", "}", ")", "@result", ",", "@success", "=", "action", "[", ":result", "]", ",", "action", "[", ":success", "]", "end" ]
Runs the machine's +before+ callbacks for this transition. Only callbacks that are configured to match the event, from state, and to state will be invoked. Once the callbacks are run, they cannot be run again until this transition is reset.
[ "Runs", "the", "machine", "s", "+", "before", "+", "callbacks", "for", "this", "transition", ".", "Only", "callbacks", "that", "are", "configured", "to", "match", "the", "event", "from", "state", "and", "to", "state", "will", "be", "invoked", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition.rb#L343-L373
train
state-machines/state_machines
lib/state_machines/transition.rb
StateMachines.Transition.after
def after unless @after_run # First resume previously paused callbacks if resume catch(:halt) do type = @success ? :after : :failure machine.callbacks[type].each {|callback| callback.call(object, context, self)} end end @after_run = true end end
ruby
def after unless @after_run # First resume previously paused callbacks if resume catch(:halt) do type = @success ? :after : :failure machine.callbacks[type].each {|callback| callback.call(object, context, self)} end end @after_run = true end end
[ "def", "after", "unless", "@after_run", "# First resume previously paused callbacks", "if", "resume", "catch", "(", ":halt", ")", "do", "type", "=", "@success", "?", ":after", ":", ":failure", "machine", ".", "callbacks", "[", "type", "]", ".", "each", "{", "|", "callback", "|", "callback", ".", "call", "(", "object", ",", "context", ",", "self", ")", "}", "end", "end", "@after_run", "=", "true", "end", "end" ]
Runs the machine's +after+ callbacks for this transition. Only callbacks that are configured to match the event, from state, and to state will be invoked. Once the callbacks are run, they cannot be run again until this transition is reset. == Halting If any callback throws a <tt>:halt</tt> exception, it will be caught and the callback chain will be automatically stopped. However, this exception will not bubble up to the caller since +after+ callbacks should never halt the execution of a +perform+.
[ "Runs", "the", "machine", "s", "+", "after", "+", "callbacks", "for", "this", "transition", ".", "Only", "callbacks", "that", "are", "configured", "to", "match", "the", "event", "from", "state", "and", "to", "state", "will", "be", "invoked", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition.rb#L388-L400
train
state-machines/state_machines
lib/state_machines/transition_collection.rb
StateMachines.TransitionCollection.run_callbacks
def run_callbacks(index = 0, &block) if transition = self[index] throw :halt unless transition.run_callbacks(:after => !skip_after) do run_callbacks(index + 1, &block) {:result => results[transition.action], :success => success?} end else persist run_actions(&block) end end
ruby
def run_callbacks(index = 0, &block) if transition = self[index] throw :halt unless transition.run_callbacks(:after => !skip_after) do run_callbacks(index + 1, &block) {:result => results[transition.action], :success => success?} end else persist run_actions(&block) end end
[ "def", "run_callbacks", "(", "index", "=", "0", ",", "&", "block", ")", "if", "transition", "=", "self", "[", "index", "]", "throw", ":halt", "unless", "transition", ".", "run_callbacks", "(", ":after", "=>", "!", "skip_after", ")", "do", "run_callbacks", "(", "index", "+", "1", ",", "block", ")", "{", ":result", "=>", "results", "[", "transition", ".", "action", "]", ",", ":success", "=>", "success?", "}", "end", "else", "persist", "run_actions", "(", "block", ")", "end", "end" ]
Runs each transition's callbacks recursively. Once all before callbacks have been executed, the transitions will then be persisted and the configured actions will be run. If any transition fails to run its callbacks, :halt will be thrown.
[ "Runs", "each", "transition", "s", "callbacks", "recursively", ".", "Once", "all", "before", "callbacks", "have", "been", "executed", "the", "transitions", "will", "then", "be", "persisted", "and", "the", "configured", "actions", "will", "be", "run", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition_collection.rb#L125-L135
train
state-machines/state_machines
lib/state_machines/transition_collection.rb
StateMachines.TransitionCollection.run_actions
def run_actions catch_exceptions do @success = if block_given? result = yield actions.each {|action| results[action] = result} !!result else actions.compact.each {|action| !skip_actions && results[action] = object.send(action)} results.values.all? end end end
ruby
def run_actions catch_exceptions do @success = if block_given? result = yield actions.each {|action| results[action] = result} !!result else actions.compact.each {|action| !skip_actions && results[action] = object.send(action)} results.values.all? end end end
[ "def", "run_actions", "catch_exceptions", "do", "@success", "=", "if", "block_given?", "result", "=", "yield", "actions", ".", "each", "{", "|", "action", "|", "results", "[", "action", "]", "=", "result", "}", "!", "!", "result", "else", "actions", ".", "compact", ".", "each", "{", "|", "action", "|", "!", "skip_actions", "&&", "results", "[", "action", "]", "=", "object", ".", "send", "(", "action", ")", "}", "results", ".", "values", ".", "all?", "end", "end", "end" ]
Runs the actions for each transition. If a block is given method, then it will be called instead of invoking each transition's action. The results of the actions will be used to determine #success?.
[ "Runs", "the", "actions", "for", "each", "transition", ".", "If", "a", "block", "is", "given", "method", "then", "it", "will", "be", "called", "instead", "of", "invoking", "each", "transition", "s", "action", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition_collection.rb#L147-L158
train
state-machines/state_machines
lib/state_machines/transition_collection.rb
StateMachines.AttributeTransitionCollection.rollback
def rollback super each {|transition| transition.machine.write(object, :event, transition.event) unless transition.transient?} end
ruby
def rollback super each {|transition| transition.machine.write(object, :event, transition.event) unless transition.transient?} end
[ "def", "rollback", "super", "each", "{", "|", "transition", "|", "transition", ".", "machine", ".", "write", "(", "object", ",", ":event", ",", "transition", ".", "event", ")", "unless", "transition", ".", "transient?", "}", "end" ]
Resets the event attribute so it can be re-evaluated if attempted again
[ "Resets", "the", "event", "attribute", "so", "it", "can", "be", "re", "-", "evaluated", "if", "attempted", "again" ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition_collection.rb#L241-L244
train
state-machines/state_machines
lib/state_machines/callback.rb
StateMachines.Callback.call
def call(object, context = {}, *args, &block) if @branch.matches?(object, context) run_methods(object, context, 0, *args, &block) true else false end end
ruby
def call(object, context = {}, *args, &block) if @branch.matches?(object, context) run_methods(object, context, 0, *args, &block) true else false end end
[ "def", "call", "(", "object", ",", "context", "=", "{", "}", ",", "*", "args", ",", "&", "block", ")", "if", "@branch", ".", "matches?", "(", "object", ",", "context", ")", "run_methods", "(", "object", ",", "context", ",", "0", ",", "args", ",", "block", ")", "true", "else", "false", "end", "end" ]
Runs the callback as long as the transition context matches the branch requirements configured for this callback. If a block is provided, it will be called when the last method has run. If a terminator has been configured and it matches the result from the evaluated method, then the callback chain should be halted.
[ "Runs", "the", "callback", "as", "long", "as", "the", "transition", "context", "matches", "the", "branch", "requirements", "configured", "for", "this", "callback", ".", "If", "a", "block", "is", "provided", "it", "will", "be", "called", "when", "the", "last", "method", "has", "run", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/callback.rb#L157-L164
train
brianmario/yajl-ruby
lib/yajl/http_stream.rb
Yajl.HttpStream.get
def get(uri, opts = {}, &block) initialize_socket(uri, opts) HttpStream::get(uri, opts, &block) rescue IOError => e raise e unless @intentional_termination end
ruby
def get(uri, opts = {}, &block) initialize_socket(uri, opts) HttpStream::get(uri, opts, &block) rescue IOError => e raise e unless @intentional_termination end
[ "def", "get", "(", "uri", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "initialize_socket", "(", "uri", ",", "opts", ")", "HttpStream", "::", "get", "(", "uri", ",", "opts", ",", "block", ")", "rescue", "IOError", "=>", "e", "raise", "e", "unless", "@intentional_termination", "end" ]
Makes a basic HTTP GET request to the URI provided allowing the user to terminate the connection
[ "Makes", "a", "basic", "HTTP", "GET", "request", "to", "the", "URI", "provided", "allowing", "the", "user", "to", "terminate", "the", "connection" ]
2f927c42bf4e1d766a1eb1f532d5924c3b61f588
https://github.com/brianmario/yajl-ruby/blob/2f927c42bf4e1d766a1eb1f532d5924c3b61f588/lib/yajl/http_stream.rb#L37-L42
train
brianmario/yajl-ruby
lib/yajl/http_stream.rb
Yajl.HttpStream.post
def post(uri, body, opts = {}, &block) initialize_socket(uri, opts) HttpStream::post(uri, body, opts, &block) rescue IOError => e raise e unless @intentional_termination end
ruby
def post(uri, body, opts = {}, &block) initialize_socket(uri, opts) HttpStream::post(uri, body, opts, &block) rescue IOError => e raise e unless @intentional_termination end
[ "def", "post", "(", "uri", ",", "body", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "initialize_socket", "(", "uri", ",", "opts", ")", "HttpStream", "::", "post", "(", "uri", ",", "body", ",", "opts", ",", "block", ")", "rescue", "IOError", "=>", "e", "raise", "e", "unless", "@intentional_termination", "end" ]
Makes a basic HTTP POST request to the URI provided allowing the user to terminate the connection
[ "Makes", "a", "basic", "HTTP", "POST", "request", "to", "the", "URI", "provided", "allowing", "the", "user", "to", "terminate", "the", "connection" ]
2f927c42bf4e1d766a1eb1f532d5924c3b61f588
https://github.com/brianmario/yajl-ruby/blob/2f927c42bf4e1d766a1eb1f532d5924c3b61f588/lib/yajl/http_stream.rb#L50-L55
train
brianmario/yajl-ruby
lib/yajl/http_stream.rb
Yajl.HttpStream.initialize_socket
def initialize_socket(uri, opts = {}) return if opts[:socket] @socket = TCPSocket.new(uri.host, uri.port) opts.merge!({:socket => @socket}) @intentional_termination = false end
ruby
def initialize_socket(uri, opts = {}) return if opts[:socket] @socket = TCPSocket.new(uri.host, uri.port) opts.merge!({:socket => @socket}) @intentional_termination = false end
[ "def", "initialize_socket", "(", "uri", ",", "opts", "=", "{", "}", ")", "return", "if", "opts", "[", ":socket", "]", "@socket", "=", "TCPSocket", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "opts", ".", "merge!", "(", "{", ":socket", "=>", "@socket", "}", ")", "@intentional_termination", "=", "false", "end" ]
Initialize socket and add it to the opts
[ "Initialize", "socket", "and", "add", "it", "to", "the", "opts" ]
2f927c42bf4e1d766a1eb1f532d5924c3b61f588
https://github.com/brianmario/yajl-ruby/blob/2f927c42bf4e1d766a1eb1f532d5924c3b61f588/lib/yajl/http_stream.rb#L205-L211
train
brentd/xray-rails
lib/xray/middleware.rb
Xray.Middleware.append_js!
def append_js!(html, after_script_name, script_name) html.sub!(script_matcher(after_script_name)) do "#{$~}\n" + helper.javascript_include_tag(script_name) end end
ruby
def append_js!(html, after_script_name, script_name) html.sub!(script_matcher(after_script_name)) do "#{$~}\n" + helper.javascript_include_tag(script_name) end end
[ "def", "append_js!", "(", "html", ",", "after_script_name", ",", "script_name", ")", "html", ".", "sub!", "(", "script_matcher", "(", "after_script_name", ")", ")", "do", "\"#{$~}\\n\"", "+", "helper", ".", "javascript_include_tag", "(", "script_name", ")", "end", "end" ]
Appends the given `script_name` after the `after_script_name`.
[ "Appends", "the", "given", "script_name", "after", "the", "after_script_name", "." ]
ab86801b55285771c567352e1784ae4346dc06a4
https://github.com/brentd/xray-rails/blob/ab86801b55285771c567352e1784ae4346dc06a4/lib/xray/middleware.rb#L114-L118
train
plataformatec/has_scope
lib/has_scope.rb
HasScope.ClassMethods.has_scope
def has_scope(*scopes, &block) options = scopes.extract_options! options.symbolize_keys! options.assert_valid_keys(:type, :only, :except, :if, :unless, :default, :as, :using, :allow_blank, :in) if options.key?(:in) options[:as] = options[:in] options[:using] = scopes end if options.key?(:using) if options.key?(:type) && options[:type] != :hash raise "You cannot use :using with another :type different than :hash" else options[:type] = :hash end options[:using] = Array(options[:using]) end options[:only] = Array(options[:only]) options[:except] = Array(options[:except]) self.scopes_configuration = scopes_configuration.dup scopes.each do |scope| scopes_configuration[scope] ||= { :as => scope, :type => :default, :block => block } scopes_configuration[scope] = self.scopes_configuration[scope].merge(options) end end
ruby
def has_scope(*scopes, &block) options = scopes.extract_options! options.symbolize_keys! options.assert_valid_keys(:type, :only, :except, :if, :unless, :default, :as, :using, :allow_blank, :in) if options.key?(:in) options[:as] = options[:in] options[:using] = scopes end if options.key?(:using) if options.key?(:type) && options[:type] != :hash raise "You cannot use :using with another :type different than :hash" else options[:type] = :hash end options[:using] = Array(options[:using]) end options[:only] = Array(options[:only]) options[:except] = Array(options[:except]) self.scopes_configuration = scopes_configuration.dup scopes.each do |scope| scopes_configuration[scope] ||= { :as => scope, :type => :default, :block => block } scopes_configuration[scope] = self.scopes_configuration[scope].merge(options) end end
[ "def", "has_scope", "(", "*", "scopes", ",", "&", "block", ")", "options", "=", "scopes", ".", "extract_options!", "options", ".", "symbolize_keys!", "options", ".", "assert_valid_keys", "(", ":type", ",", ":only", ",", ":except", ",", ":if", ",", ":unless", ",", ":default", ",", ":as", ",", ":using", ",", ":allow_blank", ",", ":in", ")", "if", "options", ".", "key?", "(", ":in", ")", "options", "[", ":as", "]", "=", "options", "[", ":in", "]", "options", "[", ":using", "]", "=", "scopes", "end", "if", "options", ".", "key?", "(", ":using", ")", "if", "options", ".", "key?", "(", ":type", ")", "&&", "options", "[", ":type", "]", "!=", ":hash", "raise", "\"You cannot use :using with another :type different than :hash\"", "else", "options", "[", ":type", "]", "=", ":hash", "end", "options", "[", ":using", "]", "=", "Array", "(", "options", "[", ":using", "]", ")", "end", "options", "[", ":only", "]", "=", "Array", "(", "options", "[", ":only", "]", ")", "options", "[", ":except", "]", "=", "Array", "(", "options", "[", ":except", "]", ")", "self", ".", "scopes_configuration", "=", "scopes_configuration", ".", "dup", "scopes", ".", "each", "do", "|", "scope", "|", "scopes_configuration", "[", "scope", "]", "||=", "{", ":as", "=>", "scope", ",", ":type", "=>", ":default", ",", ":block", "=>", "block", "}", "scopes_configuration", "[", "scope", "]", "=", "self", ".", "scopes_configuration", "[", "scope", "]", ".", "merge", "(", "options", ")", "end", "end" ]
Detects params from url and apply as scopes to your classes. == Options * <tt>:type</tt> - Checks the type of the parameter sent. If set to :boolean it just calls the named scope, without any argument. By default, it does not allow hashes or arrays to be given, except if type :hash or :array are set. * <tt>:only</tt> - In which actions the scope is applied. By default is :all. * <tt>:except</tt> - In which actions the scope is not applied. By default is :none. * <tt>:as</tt> - The key in the params hash expected to find the scope. Defaults to the scope name. * <tt>:using</tt> - If type is a hash, you can provide :using to convert the hash to a named scope call with several arguments. * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the scope should apply * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the scope should NOT apply. * <tt>:default</tt> - Default value for the scope. Whenever supplied the scope is always called. * <tt>:allow_blank</tt> - Blank values are not sent to scopes by default. Set to true to overwrite. == Block usage has_scope also accepts a block. The controller, current scope and value are yielded to the block so the user can apply the scope on its own. This is useful in case we need to manipulate the given value: has_scope :category do |controller, scope, value| value != "all" ? scope.by_category(value) : scope end has_scope :not_voted_by_me, :type => :boolean do |controller, scope| scope.not_voted_by(controller.current_user.id) end
[ "Detects", "params", "from", "url", "and", "apply", "as", "scopes", "to", "your", "classes", "." ]
ac9f4e68ce14f3f4b94fd323d7b9a0acbab4cfb3
https://github.com/plataformatec/has_scope/blob/ac9f4e68ce14f3f4b94fd323d7b9a0acbab4cfb3/lib/has_scope.rb#L64-L93
train
ohler55/ox
lib/ox/element.rb
Ox.Element.attr_match
def attr_match(cond) cond.each_pair { |k,v| return false unless v == @attributes[k.to_sym] || v == @attributes[k.to_s] } true end
ruby
def attr_match(cond) cond.each_pair { |k,v| return false unless v == @attributes[k.to_sym] || v == @attributes[k.to_s] } true end
[ "def", "attr_match", "(", "cond", ")", "cond", ".", "each_pair", "{", "|", "k", ",", "v", "|", "return", "false", "unless", "v", "==", "@attributes", "[", "k", ".", "to_sym", "]", "||", "v", "==", "@attributes", "[", "k", ".", "to_s", "]", "}", "true", "end" ]
Return true if all the key-value pairs in the cond Hash match the @attributes key-values.
[ "Return", "true", "if", "all", "the", "key", "-", "value", "pairs", "in", "the", "cond", "Hash", "match", "the" ]
f5b618285a0b9c885aa86dd9d51188fce2d60856
https://github.com/ohler55/ox/blob/f5b618285a0b9c885aa86dd9d51188fce2d60856/lib/ox/element.rb#L106-L109
train
ohler55/ox
lib/ox/element.rb
Ox.Element.each
def each(cond=nil) if cond.nil? nodes.each { |n| yield(n) } else cond = cond.to_s if cond.is_a?(Symbol) if cond.is_a?(String) nodes.each { |n| yield(n) if n.is_a?(Element) && cond == n.name } elsif cond.is_a?(Hash) nodes.each { |n| yield(n) if n.is_a?(Element) && n.attr_match(cond) } end end end
ruby
def each(cond=nil) if cond.nil? nodes.each { |n| yield(n) } else cond = cond.to_s if cond.is_a?(Symbol) if cond.is_a?(String) nodes.each { |n| yield(n) if n.is_a?(Element) && cond == n.name } elsif cond.is_a?(Hash) nodes.each { |n| yield(n) if n.is_a?(Element) && n.attr_match(cond) } end end end
[ "def", "each", "(", "cond", "=", "nil", ")", "if", "cond", ".", "nil?", "nodes", ".", "each", "{", "|", "n", "|", "yield", "(", "n", ")", "}", "else", "cond", "=", "cond", ".", "to_s", "if", "cond", ".", "is_a?", "(", "Symbol", ")", "if", "cond", ".", "is_a?", "(", "String", ")", "nodes", ".", "each", "{", "|", "n", "|", "yield", "(", "n", ")", "if", "n", ".", "is_a?", "(", "Element", ")", "&&", "cond", "==", "n", ".", "name", "}", "elsif", "cond", ".", "is_a?", "(", "Hash", ")", "nodes", ".", "each", "{", "|", "n", "|", "yield", "(", "n", ")", "if", "n", ".", "is_a?", "(", "Element", ")", "&&", "n", ".", "attr_match", "(", "cond", ")", "}", "end", "end", "end" ]
Iterate over each child of the instance yielding according to the cond argument value. If the cond argument is nil then all child nodes are yielded to. If cond is a string then only the child Elements with a matching name will be yielded to. If the cond is a Hash then the keys-value pairs in the cond must match the child attribute values with the same keys. Any other cond type will yield to nothing.
[ "Iterate", "over", "each", "child", "of", "the", "instance", "yielding", "according", "to", "the", "cond", "argument", "value", ".", "If", "the", "cond", "argument", "is", "nil", "then", "all", "child", "nodes", "are", "yielded", "to", ".", "If", "cond", "is", "a", "string", "then", "only", "the", "child", "Elements", "with", "a", "matching", "name", "will", "be", "yielded", "to", ".", "If", "the", "cond", "is", "a", "Hash", "then", "the", "keys", "-", "value", "pairs", "in", "the", "cond", "must", "match", "the", "child", "attribute", "values", "with", "the", "same", "keys", ".", "Any", "other", "cond", "type", "will", "yield", "to", "nothing", "." ]
f5b618285a0b9c885aa86dd9d51188fce2d60856
https://github.com/ohler55/ox/blob/f5b618285a0b9c885aa86dd9d51188fce2d60856/lib/ox/element.rb#L117-L128
train
ohler55/ox
lib/ox/element.rb
Ox.Element.remove_children
def remove_children(*children) return self if children.compact.empty? recursive_children_removal(children.compact.map { |c| c.object_id }) self end
ruby
def remove_children(*children) return self if children.compact.empty? recursive_children_removal(children.compact.map { |c| c.object_id }) self end
[ "def", "remove_children", "(", "*", "children", ")", "return", "self", "if", "children", ".", "compact", ".", "empty?", "recursive_children_removal", "(", "children", ".", "compact", ".", "map", "{", "|", "c", "|", "c", ".", "object_id", "}", ")", "self", "end" ]
Remove all the children matching the path provided Examples are: * <code>element.remove_children(Ox:Element)</code> removes the element passed as argument if child of the element. * <code>element.remove_children(Ox:Element, Ox:Element)</code> removes the list of elements passed as argument if children of the element. - +children+ [Array] array of OX
[ "Remove", "all", "the", "children", "matching", "the", "path", "provided" ]
f5b618285a0b9c885aa86dd9d51188fce2d60856
https://github.com/ohler55/ox/blob/f5b618285a0b9c885aa86dd9d51188fce2d60856/lib/ox/element.rb#L192-L196
train
ohler55/ox
lib/ox/element.rb
Ox.Element.recursive_children_removal
def recursive_children_removal(found) return if found.empty? nodes.tap do |ns| # found.delete(n.object_id) stops looking for an already found object_id ns.delete_if { |n| found.include?(n.object_id) ? found.delete(n.object_id) : false } nodes.each do |n| n.send(:recursive_children_removal, found) if n.is_a?(Ox::Element) end end end
ruby
def recursive_children_removal(found) return if found.empty? nodes.tap do |ns| # found.delete(n.object_id) stops looking for an already found object_id ns.delete_if { |n| found.include?(n.object_id) ? found.delete(n.object_id) : false } nodes.each do |n| n.send(:recursive_children_removal, found) if n.is_a?(Ox::Element) end end end
[ "def", "recursive_children_removal", "(", "found", ")", "return", "if", "found", ".", "empty?", "nodes", ".", "tap", "do", "|", "ns", "|", "# found.delete(n.object_id) stops looking for an already found object_id", "ns", ".", "delete_if", "{", "|", "n", "|", "found", ".", "include?", "(", "n", ".", "object_id", ")", "?", "found", ".", "delete", "(", "n", ".", "object_id", ")", ":", "false", "}", "nodes", ".", "each", "do", "|", "n", "|", "n", ".", "send", "(", ":recursive_children_removal", ",", "found", ")", "if", "n", ".", "is_a?", "(", "Ox", "::", "Element", ")", "end", "end", "end" ]
Removes recursively children for nodes and sub_nodes - +found+ [Array] An array of Ox::Element
[ "Removes", "recursively", "children", "for", "nodes", "and", "sub_nodes" ]
f5b618285a0b9c885aa86dd9d51188fce2d60856
https://github.com/ohler55/ox/blob/f5b618285a0b9c885aa86dd9d51188fce2d60856/lib/ox/element.rb#L418-L427
train
igor-makarov/xcake
lib/xcake/visitor.rb
Xcake.Visitor.visit
def visit(item) item_name = item_name(item) method = "visit_#{item_name}" send(method, item) if respond_to? method end
ruby
def visit(item) item_name = item_name(item) method = "visit_#{item_name}" send(method, item) if respond_to? method end
[ "def", "visit", "(", "item", ")", "item_name", "=", "item_name", "(", "item", ")", "method", "=", "\"visit_#{item_name}\"", "send", "(", "method", ",", "item", ")", "if", "respond_to?", "method", "end" ]
This is called when a visitor is visiting a visitable item. By default this method calls the method `visit_<visitable classname>` so make sure you've created a method for each visitable you intend to visit. @param [Visitable] visitable the visitable item the visitor is visiting
[ "This", "is", "called", "when", "a", "visitor", "is", "visiting", "a", "visitable", "item", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/visitor.rb#L41-L46
train
igor-makarov/xcake
lib/xcake/visitor.rb
Xcake.Visitor.leave
def leave(item) item_name = item_name(item) method = "leave_#{item_name}" send(method, item) if respond_to? method end
ruby
def leave(item) item_name = item_name(item) method = "leave_#{item_name}" send(method, item) if respond_to? method end
[ "def", "leave", "(", "item", ")", "item_name", "=", "item_name", "(", "item", ")", "method", "=", "\"leave_#{item_name}\"", "send", "(", "method", ",", "item", ")", "if", "respond_to?", "method", "end" ]
This is called when a visitor is leaving a visitable item. By default this method calls the method `leave_<visitable classname>` so make sure you've created a method for each visitable you intend to visit. @param [Visitable] visitable the visitable item the visitor has left
[ "This", "is", "called", "when", "a", "visitor", "is", "leaving", "a", "visitable", "item", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/visitor.rb#L59-L64
train
igor-makarov/xcake
lib/xcake/dsl/target/sugar.rb
Xcake.Target.copy_files_build_phase
def copy_files_build_phase(name, &block) phase = CopyFilesBuildPhase.new(&block) phase.name = name build_phases << phase phase end
ruby
def copy_files_build_phase(name, &block) phase = CopyFilesBuildPhase.new(&block) phase.name = name build_phases << phase phase end
[ "def", "copy_files_build_phase", "(", "name", ",", "&", "block", ")", "phase", "=", "CopyFilesBuildPhase", ".", "new", "(", "block", ")", "phase", ".", "name", "=", "name", "build_phases", "<<", "phase", "phase", "end" ]
Creates a new Copy Files build phase for the target @param [String] name the name to use for the build phase @param [Proc] block an optional block that configures the build phase through the DSL. @return [CopyFilesBuildPhase] the new xcode build phase
[ "Creates", "a", "new", "Copy", "Files", "build", "phase", "for", "the", "target" ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/target/sugar.rb#L16-L21
train
igor-makarov/xcake
lib/xcake/dsl/target/sugar.rb
Xcake.Target.pre_shell_script_build_phase
def pre_shell_script_build_phase(name, script, &block) phase = ShellScriptBuildPhase.new(&block) phase.name = name phase.script = script pinned_build_phases << phase phase end
ruby
def pre_shell_script_build_phase(name, script, &block) phase = ShellScriptBuildPhase.new(&block) phase.name = name phase.script = script pinned_build_phases << phase phase end
[ "def", "pre_shell_script_build_phase", "(", "name", ",", "script", ",", "&", "block", ")", "phase", "=", "ShellScriptBuildPhase", ".", "new", "(", "block", ")", "phase", ".", "name", "=", "name", "phase", ".", "script", "=", "script", "pinned_build_phases", "<<", "phase", "phase", "end" ]
Creates a new Shell Script build phase for the target before all of the other build phases @param [String] name the name to use for the build phase @param [Proc] block an optional block that configures the build phase through the DSL. @return [ShellScriptBuildPhase] the new xcode build phase
[ "Creates", "a", "new", "Shell", "Script", "build", "phase", "for", "the", "target", "before", "all", "of", "the", "other", "build", "phases" ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/target/sugar.rb#L48-L54
train
igor-makarov/xcake
lib/xcake/dsl/target/sugar.rb
Xcake.Target.shell_script_build_phase
def shell_script_build_phase(name, script, &block) phase = ShellScriptBuildPhase.new(&block) phase.name = name phase.script = script build_phases << phase phase end
ruby
def shell_script_build_phase(name, script, &block) phase = ShellScriptBuildPhase.new(&block) phase.name = name phase.script = script build_phases << phase phase end
[ "def", "shell_script_build_phase", "(", "name", ",", "script", ",", "&", "block", ")", "phase", "=", "ShellScriptBuildPhase", ".", "new", "(", "block", ")", "phase", ".", "name", "=", "name", "phase", ".", "script", "=", "script", "build_phases", "<<", "phase", "phase", "end" ]
Creates a new Shell Script build phase for the target @param [String] name the name to use for the build phase @param [Proc] block an optional block that configures the build phase through the DSL. @return [ShellScriptBuildPhase] the new xcode build phase
[ "Creates", "a", "new", "Shell", "Script", "build", "phase", "for", "the", "target" ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/target/sugar.rb#L67-L73
train
igor-makarov/xcake
lib/xcake/dsl/target/sugar.rb
Xcake.Target.build_rule
def build_rule(name, file_type, output_files, output_files_compiler_flags, script, &block) rule = BuildRule.new(&block) rule.name = name rule.file_type = file_type rule.output_files = output_files rule.output_files_compiler_flags = output_files_compiler_flags rule.script = script build_rules << rule rule end
ruby
def build_rule(name, file_type, output_files, output_files_compiler_flags, script, &block) rule = BuildRule.new(&block) rule.name = name rule.file_type = file_type rule.output_files = output_files rule.output_files_compiler_flags = output_files_compiler_flags rule.script = script build_rules << rule rule end
[ "def", "build_rule", "(", "name", ",", "file_type", ",", "output_files", ",", "output_files_compiler_flags", ",", "script", ",", "&", "block", ")", "rule", "=", "BuildRule", ".", "new", "(", "block", ")", "rule", ".", "name", "=", "name", "rule", ".", "file_type", "=", "file_type", "rule", ".", "output_files", "=", "output_files", "rule", ".", "output_files_compiler_flags", "=", "output_files_compiler_flags", "rule", ".", "script", "=", "script", "build_rules", "<<", "rule", "rule", "end" ]
Creates a new build rule for the target @param [String] name the name to use for the build rule @param [Proc] block an optional block that configures the build rule through the DSL. @return [BuildRule] the new xcode build rule
[ "Creates", "a", "new", "build", "rule", "for", "the", "target" ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/target/sugar.rb#L86-L95
train
igor-makarov/xcake
lib/xcake/dsl/configurable.rb
Xcake.Configurable.configuration
def configuration(name, type) default_settings = default_settings_for_type(type) configurations = configurations_of_type(type) build_configuration = if name.nil? configurations.first else configurations.detect do |c| c.name == name.to_s end end if build_configuration.nil? name = type.to_s.capitalize if name.nil? build_configuration = Configuration.new(name) do |b| b.type = type b.settings.merge!(default_settings) yield(b) if block_given? end @configurations ||= [] @configurations << build_configuration end build_configuration end
ruby
def configuration(name, type) default_settings = default_settings_for_type(type) configurations = configurations_of_type(type) build_configuration = if name.nil? configurations.first else configurations.detect do |c| c.name == name.to_s end end if build_configuration.nil? name = type.to_s.capitalize if name.nil? build_configuration = Configuration.new(name) do |b| b.type = type b.settings.merge!(default_settings) yield(b) if block_given? end @configurations ||= [] @configurations << build_configuration end build_configuration end
[ "def", "configuration", "(", "name", ",", "type", ")", "default_settings", "=", "default_settings_for_type", "(", "type", ")", "configurations", "=", "configurations_of_type", "(", "type", ")", "build_configuration", "=", "if", "name", ".", "nil?", "configurations", ".", "first", "else", "configurations", ".", "detect", "do", "|", "c", "|", "c", ".", "name", "==", "name", ".", "to_s", "end", "end", "if", "build_configuration", ".", "nil?", "name", "=", "type", ".", "to_s", ".", "capitalize", "if", "name", ".", "nil?", "build_configuration", "=", "Configuration", ".", "new", "(", "name", ")", "do", "|", "b", "|", "b", ".", "type", "=", "type", "b", ".", "settings", ".", "merge!", "(", "default_settings", ")", "yield", "(", "b", ")", "if", "block_given?", "end", "@configurations", "||=", "[", "]", "@configurations", "<<", "build_configuration", "end", "build_configuration", "end" ]
This either finds a configuration with the same name and type or creates one. @return [Configuration] the new or existing configuration
[ "This", "either", "finds", "a", "configuration", "with", "the", "same", "name", "and", "type", "or", "creates", "one", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/configurable.rb#L94-L122
train
igor-makarov/xcake
lib/xcake/dsl/project/sugar.rb
Xcake.Project.application_for
def application_for(platform, deployment_target, language = :objc) target do |t| t.type = :application t.platform = platform t.deployment_target = deployment_target t.language = language yield(t) if block_given? end end
ruby
def application_for(platform, deployment_target, language = :objc) target do |t| t.type = :application t.platform = platform t.deployment_target = deployment_target t.language = language yield(t) if block_given? end end
[ "def", "application_for", "(", "platform", ",", "deployment_target", ",", "language", "=", ":objc", ")", "target", "do", "|", "t", "|", "t", ".", "type", "=", ":application", "t", ".", "platform", "=", "platform", "t", ".", "deployment_target", "=", "deployment_target", "t", ".", "language", "=", "language", "yield", "(", "t", ")", "if", "block_given?", "end", "end" ]
Defines a new application target. @param [Symbol] platform platform for the application, can be either `:ios`, `:osx`, `:tvos` or `:watchos`. @param [Float] deployment_target the minimum deployment version for the platform. @param [Symbol] language language for application, can be either `:objc` or `:swift`. @param [Proc] block an optional block that configures the target through the DSL. @return [Target] the application target the newly created application target
[ "Defines", "a", "new", "application", "target", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/project/sugar.rb#L34-L43
train
igor-makarov/xcake
lib/xcake/dsl/project/sugar.rb
Xcake.Project.extension_for
def extension_for(host_target) target = target do |t| t.type = :app_extension t.platform = host_target.platform t.deployment_target = host_target.deployment_target t.language = host_target.language end host_target.target_dependencies << target yield(target) if block_given? target end
ruby
def extension_for(host_target) target = target do |t| t.type = :app_extension t.platform = host_target.platform t.deployment_target = host_target.deployment_target t.language = host_target.language end host_target.target_dependencies << target yield(target) if block_given? target end
[ "def", "extension_for", "(", "host_target", ")", "target", "=", "target", "do", "|", "t", "|", "t", ".", "type", "=", ":app_extension", "t", ".", "platform", "=", "host_target", ".", "platform", "t", ".", "deployment_target", "=", "host_target", ".", "deployment_target", "t", ".", "language", "=", "host_target", ".", "language", "end", "host_target", ".", "target_dependencies", "<<", "target", "yield", "(", "target", ")", "if", "block_given?", "target", "end" ]
Defines a extension target. @param [Target] host target host target for which the extension is for. @param [Proc] block an optional block that configures the target through the DSL. @return [Target] the extension target the newly created extension target
[ "Defines", "a", "extension", "target", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/project/sugar.rb#L126-L139
train
igor-makarov/xcake
lib/xcake/dsl/project/sugar.rb
Xcake.Project.watch_app_for
def watch_app_for(host_target, deployment_target, language = :objc) watch_app_target = target do |t| t.name = "#{host_target.name}-Watch" t.type = :watch2_app t.platform = :watchos t.deployment_target = deployment_target t.language = language end watch_extension_target = target do |t| t.name = "#{host_target.name}-Watch Extension" t.type = :watch2_extension t.platform = :watchos t.deployment_target = deployment_target t.language = language end host_target.target_dependencies << watch_app_target watch_app_target.target_dependencies << watch_extension_target yield(watch_app_target, watch_extension_target) if block_given? nil end
ruby
def watch_app_for(host_target, deployment_target, language = :objc) watch_app_target = target do |t| t.name = "#{host_target.name}-Watch" t.type = :watch2_app t.platform = :watchos t.deployment_target = deployment_target t.language = language end watch_extension_target = target do |t| t.name = "#{host_target.name}-Watch Extension" t.type = :watch2_extension t.platform = :watchos t.deployment_target = deployment_target t.language = language end host_target.target_dependencies << watch_app_target watch_app_target.target_dependencies << watch_extension_target yield(watch_app_target, watch_extension_target) if block_given? nil end
[ "def", "watch_app_for", "(", "host_target", ",", "deployment_target", ",", "language", "=", ":objc", ")", "watch_app_target", "=", "target", "do", "|", "t", "|", "t", ".", "name", "=", "\"#{host_target.name}-Watch\"", "t", ".", "type", "=", ":watch2_app", "t", ".", "platform", "=", ":watchos", "t", ".", "deployment_target", "=", "deployment_target", "t", ".", "language", "=", "language", "end", "watch_extension_target", "=", "target", "do", "|", "t", "|", "t", ".", "name", "=", "\"#{host_target.name}-Watch Extension\"", "t", ".", "type", "=", ":watch2_extension", "t", ".", "platform", "=", ":watchos", "t", ".", "deployment_target", "=", "deployment_target", "t", ".", "language", "=", "language", "end", "host_target", ".", "target_dependencies", "<<", "watch_app_target", "watch_app_target", ".", "target_dependencies", "<<", "watch_extension_target", "yield", "(", "watch_app_target", ",", "watch_extension_target", ")", "if", "block_given?", "nil", "end" ]
Defines targets for watch app. @param [Target] watch app's compantion app iOS target for the watch app @param [Proc] block an optional block that configures the targets through the DSL. @return Void
[ "Defines", "targets", "for", "watch", "app", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/project/sugar.rb#L151-L176
train
igor-makarov/xcake
lib/xcake/dsl/target.rb
Xcake.Target.default_system_frameworks_for
def default_system_frameworks_for(platform) case platform when :ios %w(Foundation UIKit) when :osx %w(Cocoa) when :tvos %w(Foundation UIKit) when :watchos %w(Foundation UIKit WatchKit) else abort 'Platform not supported!' end end
ruby
def default_system_frameworks_for(platform) case platform when :ios %w(Foundation UIKit) when :osx %w(Cocoa) when :tvos %w(Foundation UIKit) when :watchos %w(Foundation UIKit WatchKit) else abort 'Platform not supported!' end end
[ "def", "default_system_frameworks_for", "(", "platform", ")", "case", "platform", "when", ":ios", "%w(", "Foundation", "UIKit", ")", "when", ":osx", "%w(", "Cocoa", ")", "when", ":tvos", "%w(", "Foundation", "UIKit", ")", "when", ":watchos", "%w(", "Foundation", "UIKit", "WatchKit", ")", "else", "abort", "'Platform not supported!'", "end", "end" ]
Returns an array of default system frameworks to use for a given platform. @param [Symbol] platform platform the frameworks are for. @return [Array<String>] system frameworks to use
[ "Returns", "an", "array", "of", "default", "system", "frameworks", "to", "use", "for", "a", "given", "platform", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/target.rb#L256-L269
train
amatsuda/stateful_enum
lib/stateful_enum/state_inspection.rb
StatefulEnum.StateInspector.possible_states
def possible_states col = @stateful_enum.instance_variable_get :@column possible_events.flat_map {|e| e.instance_variable_get(:@transitions)[@model_instance.send(col).to_sym].first } end
ruby
def possible_states col = @stateful_enum.instance_variable_get :@column possible_events.flat_map {|e| e.instance_variable_get(:@transitions)[@model_instance.send(col).to_sym].first } end
[ "def", "possible_states", "col", "=", "@stateful_enum", ".", "instance_variable_get", ":@column", "possible_events", ".", "flat_map", "{", "|", "e", "|", "e", ".", "instance_variable_get", "(", ":@transitions", ")", "[", "@model_instance", ".", "send", "(", "col", ")", ".", "to_sym", "]", ".", "first", "}", "end" ]
List of transitionable states from the current state
[ "List", "of", "transitionable", "states", "from", "the", "current", "state" ]
38eafa5e05869e10b8e7f287185accea5913cfd6
https://github.com/amatsuda/stateful_enum/blob/38eafa5e05869e10b8e7f287185accea5913cfd6/lib/stateful_enum/state_inspection.rb#L36-L39
train
tzinfo/tzinfo
lib/tzinfo/timezone.rb
TZInfo.Timezone.to_local
def to_local(time) raise ArgumentError, 'time must be specified' unless time Timestamp.for(time) do |ts| TimestampWithOffset.set_timezone_offset(ts, period_for(ts).offset) end end
ruby
def to_local(time) raise ArgumentError, 'time must be specified' unless time Timestamp.for(time) do |ts| TimestampWithOffset.set_timezone_offset(ts, period_for(ts).offset) end end
[ "def", "to_local", "(", "time", ")", "raise", "ArgumentError", ",", "'time must be specified'", "unless", "time", "Timestamp", ".", "for", "(", "time", ")", "do", "|", "ts", "|", "TimestampWithOffset", ".", "set_timezone_offset", "(", "ts", ",", "period_for", "(", "ts", ")", ".", "offset", ")", "end", "end" ]
Converts a time to the local time for the time zone. The result will be of type {TimeWithOffset} (if passed a `Time`), {DateTimeWithOffset} (if passed a `DateTime`) or {TimestampWithOffset} (if passed a {Timestamp}). {TimeWithOffset}, {DateTimeWithOffset} and {TimestampWithOffset} are subclasses of `Time`, `DateTime` and {Timestamp} that provide additional information about the local result. Unlike {utc_to_local}, {to_local} takes the UTC offset of the given time into consideration. @param time [Object] a `Time`, `DateTime` or {Timestamp}. @return [Object] the local equivalent of `time` as a {TimeWithOffset}, {DateTimeWithOffset} or {TimestampWithOffset}. @raise [ArgumentError] if `time` is `nil`. @raise [ArgumentError] if `time` is a {Timestamp} that does not have a specified UTC offset.
[ "Converts", "a", "time", "to", "the", "local", "time", "for", "the", "time", "zone", "." ]
8fdf06ed9a4b935864e19794187d091219de481a
https://github.com/tzinfo/tzinfo/blob/8fdf06ed9a4b935864e19794187d091219de481a/lib/tzinfo/timezone.rb#L548-L554
train
tzinfo/tzinfo
lib/tzinfo/timezone.rb
TZInfo.Timezone.utc_to_local
def utc_to_local(utc_time) raise ArgumentError, 'utc_time must be specified' unless utc_time Timestamp.for(utc_time, :treat_as_utc) do |ts| to_local(ts) end end
ruby
def utc_to_local(utc_time) raise ArgumentError, 'utc_time must be specified' unless utc_time Timestamp.for(utc_time, :treat_as_utc) do |ts| to_local(ts) end end
[ "def", "utc_to_local", "(", "utc_time", ")", "raise", "ArgumentError", ",", "'utc_time must be specified'", "unless", "utc_time", "Timestamp", ".", "for", "(", "utc_time", ",", ":treat_as_utc", ")", "do", "|", "ts", "|", "to_local", "(", "ts", ")", "end", "end" ]
Converts a time in UTC to the local time for the time zone. The result will be of type {TimeWithOffset} (if passed a `Time`), {DateTimeWithOffset} (if passed a `DateTime`) or {TimestampWithOffset} (if passed a {Timestamp}). {TimeWithOffset}, {DateTimeWithOffset} and {TimestampWithOffset} are subclasses of `Time`, `DateTime` and {Timestamp} that provide additional information about the local result. The UTC offset of the `utc_time` parameter is ignored (it is treated as a UTC time). Use the {to_local} method instead if the the UTC offset of the time needs to be taken into consideration. @param utc_time [Object] a `Time`, `DateTime` or {Timestamp}. @return [Object] the local equivalent of `utc_time` as a {TimeWithOffset}, {DateTimeWithOffset} or {TimestampWithOffset}. @raise [ArgumentError] if `utc_time` is `nil`.
[ "Converts", "a", "time", "in", "UTC", "to", "the", "local", "time", "for", "the", "time", "zone", "." ]
8fdf06ed9a4b935864e19794187d091219de481a
https://github.com/tzinfo/tzinfo/blob/8fdf06ed9a4b935864e19794187d091219de481a/lib/tzinfo/timezone.rb#L572-L578
train
tzinfo/tzinfo
lib/tzinfo/timezone.rb
TZInfo.Timezone.local_to_utc
def local_to_utc(local_time, dst = Timezone.default_dst) raise ArgumentError, 'local_time must be specified' unless local_time Timestamp.for(local_time, :ignore) do |ts| period = if block_given? period_for_local(ts, dst) {|periods| yield periods } else period_for_local(ts, dst) end ts.add_and_set_utc_offset(-period.observed_utc_offset, :utc) end end
ruby
def local_to_utc(local_time, dst = Timezone.default_dst) raise ArgumentError, 'local_time must be specified' unless local_time Timestamp.for(local_time, :ignore) do |ts| period = if block_given? period_for_local(ts, dst) {|periods| yield periods } else period_for_local(ts, dst) end ts.add_and_set_utc_offset(-period.observed_utc_offset, :utc) end end
[ "def", "local_to_utc", "(", "local_time", ",", "dst", "=", "Timezone", ".", "default_dst", ")", "raise", "ArgumentError", ",", "'local_time must be specified'", "unless", "local_time", "Timestamp", ".", "for", "(", "local_time", ",", ":ignore", ")", "do", "|", "ts", "|", "period", "=", "if", "block_given?", "period_for_local", "(", "ts", ",", "dst", ")", "{", "|", "periods", "|", "yield", "periods", "}", "else", "period_for_local", "(", "ts", ",", "dst", ")", "end", "ts", ".", "add_and_set_utc_offset", "(", "-", "period", ".", "observed_utc_offset", ",", ":utc", ")", "end", "end" ]
Converts a local time for the time zone to UTC. The result will either be a `Time`, `DateTime` or {Timestamp} according to the type of the `local_time` parameter. The UTC offset of the `local_time` parameter is ignored (it is treated as a time in the time zone represented by `self`). _Warning:_ There are local times that have no equivalent UTC times (for example, during the transition from standard time to daylight savings time). There are also local times that have more than one UTC equivalent (for example, during the transition from daylight savings time to standard time). In the first case (no equivalent UTC time), a {PeriodNotFound} exception will be raised. In the second case (more than one equivalent UTC time), an {AmbiguousTime} exception will be raised unless the optional `dst` parameter or block handles the ambiguity. If the ambiguity is due to a transition from daylight savings time to standard time, the `dst` parameter can be used to select whether the daylight savings time or local time is used. For example, the following code would raise an {AmbiguousTime} exception: tz = TZInfo::Timezone.get('America/New_York') tz.period_for_local(Time.new(2004,10,31,1,30,0)) Specifying `dst = true` would select the daylight savings period from April to October 2004. Specifying `dst = false` would return the standard time period from October 2004 to April 2005. The `dst` parameter will not be able to resolve an ambiguity resulting from the clocks being set back without changing from daylight savings time to standard time. In this case, if a block is specified, it will be called to resolve the ambiguity. The block must take a single parameter - an `Array` of {TimezonePeriod}s that need to be resolved. The block can select and return a single {TimezonePeriod} or return `nil` or an empty `Array` to cause an {AmbiguousTime} exception to be raised. The default value of the `dst` parameter can be specified using {Timezone.default_dst=}. @param local_time [Object] a `Time`, `DateTime` or {Timestamp}. @param dst [Boolean] whether to resolve ambiguous local times by always selecting the period observing daylight savings time (`true`), always selecting the period observing standard time (`false`), or leaving the ambiguity unresolved (`nil`). @yield [periods] if the `dst` parameter did not resolve an ambiguity, an optional block is yielded to. @yieldparam periods [Array<TimezonePeriod>] an `Array` containing all the {TimezonePeriod}s that still match `local_time` after applying the `dst` parameter. @yieldreturn [Object] to resolve the ambiguity: a chosen {TimezonePeriod} or an `Array` containing a chosen {TimezonePeriod}; to leave the ambiguity unresolved: an empty `Array`, an `Array` containing more than one {TimezonePeriod}, or `nil`. @return [Object] the UTC equivalent of `local_time` as a `Time`, `DateTime` or {Timestamp}. @raise [ArgumentError] if `local_time` is `nil`. @raise [PeriodNotFound] if `local_time` is not valid for the time zone (there is no equivalent UTC time). @raise [AmbiguousTime] if `local_time` was ambiguous for the time zone and the `dst` parameter or block did not resolve the ambiguity.
[ "Converts", "a", "local", "time", "for", "the", "time", "zone", "to", "UTC", "." ]
8fdf06ed9a4b935864e19794187d091219de481a
https://github.com/tzinfo/tzinfo/blob/8fdf06ed9a4b935864e19794187d091219de481a/lib/tzinfo/timezone.rb#L645-L657
train
tzinfo/tzinfo
lib/tzinfo/data_source.rb
TZInfo.DataSource.try_with_encoding
def try_with_encoding(string, encoding) result = yield string return result if result unless encoding == string.encoding string = string.encode(encoding) yield string end end
ruby
def try_with_encoding(string, encoding) result = yield string return result if result unless encoding == string.encoding string = string.encode(encoding) yield string end end
[ "def", "try_with_encoding", "(", "string", ",", "encoding", ")", "result", "=", "yield", "string", "return", "result", "if", "result", "unless", "encoding", "==", "string", ".", "encoding", "string", "=", "string", ".", "encode", "(", "encoding", ")", "yield", "string", "end", "end" ]
Tries an operation using `string` directly. If the operation fails, the string is copied and encoded with `encoding` and the operation is tried again. @param string [String] The `String` to perform the operation on. @param encoding [Encoding] The `Encoding` to use if the initial attempt fails. @yield [s] the caller will be yielded to once or twice to attempt the operation. @yieldparam s [String] either `string` or an encoded copy of `string`. @yieldreturn [Object] The result of the operation. Must be truthy if successful. @return [Object] the result of the operation or `nil` if the first attempt fails and `string` is already encoded with `encoding`.
[ "Tries", "an", "operation", "using", "string", "directly", ".", "If", "the", "operation", "fails", "the", "string", "is", "copied", "and", "encoded", "with", "encoding", "and", "the", "operation", "is", "tried", "again", "." ]
8fdf06ed9a4b935864e19794187d091219de481a
https://github.com/tzinfo/tzinfo/blob/8fdf06ed9a4b935864e19794187d091219de481a/lib/tzinfo/data_source.rb#L425-L433
train
markets/invisible_captcha
lib/invisible_captcha/view_helpers.rb
InvisibleCaptcha.ViewHelpers.invisible_captcha
def invisible_captcha(honeypot = nil, scope = nil, options = {}) if InvisibleCaptcha.timestamp_enabled session[:invisible_captcha_timestamp] = Time.zone.now.iso8601 end build_invisible_captcha(honeypot, scope, options) end
ruby
def invisible_captcha(honeypot = nil, scope = nil, options = {}) if InvisibleCaptcha.timestamp_enabled session[:invisible_captcha_timestamp] = Time.zone.now.iso8601 end build_invisible_captcha(honeypot, scope, options) end
[ "def", "invisible_captcha", "(", "honeypot", "=", "nil", ",", "scope", "=", "nil", ",", "options", "=", "{", "}", ")", "if", "InvisibleCaptcha", ".", "timestamp_enabled", "session", "[", ":invisible_captcha_timestamp", "]", "=", "Time", ".", "zone", ".", "now", ".", "iso8601", "end", "build_invisible_captcha", "(", "honeypot", ",", "scope", ",", "options", ")", "end" ]
Builds the honeypot html @param honeypot [Symbol] name of honeypot, ie: subtitle => input name: subtitle @param scope [Symbol] name of honeypot scope, ie: topic => input name: topic[subtitle] @param options [Hash] html_options for input and invisible_captcha options @return [String] the generated html
[ "Builds", "the", "honeypot", "html" ]
3da1ead83efa20579c8e1fbb7e040fc4e5810eb2
https://github.com/markets/invisible_captcha/blob/3da1ead83efa20579c8e1fbb7e040fc4e5810eb2/lib/invisible_captcha/view_helpers.rb#L10-L15
train
leejarvis/slop
lib/slop/result.rb
Slop.Result.fetch
def fetch(flag) o = option(flag) if o.nil? cleaned_key = clean_key(flag) raise UnknownOption.new("option not found: '#{cleaned_key}'", "#{cleaned_key}") else o.value end end
ruby
def fetch(flag) o = option(flag) if o.nil? cleaned_key = clean_key(flag) raise UnknownOption.new("option not found: '#{cleaned_key}'", "#{cleaned_key}") else o.value end end
[ "def", "fetch", "(", "flag", ")", "o", "=", "option", "(", "flag", ")", "if", "o", ".", "nil?", "cleaned_key", "=", "clean_key", "(", "flag", ")", "raise", "UnknownOption", ".", "new", "(", "\"option not found: '#{cleaned_key}'\"", ",", "\"#{cleaned_key}\"", ")", "else", "o", ".", "value", "end", "end" ]
Returns an option's value, raises UnknownOption if the option does not exist.
[ "Returns", "an", "option", "s", "value", "raises", "UnknownOption", "if", "the", "option", "does", "not", "exist", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/result.rb#L24-L32
train
leejarvis/slop
lib/slop/result.rb
Slop.Result.[]=
def []=(flag, value) if o = option(flag) o.value = value else raise ArgumentError, "no option with flag `#{flag}'" end end
ruby
def []=(flag, value) if o = option(flag) o.value = value else raise ArgumentError, "no option with flag `#{flag}'" end end
[ "def", "[]=", "(", "flag", ",", "value", ")", "if", "o", "=", "option", "(", "flag", ")", "o", ".", "value", "=", "value", "else", "raise", "ArgumentError", ",", "\"no option with flag `#{flag}'\"", "end", "end" ]
Set the value for an option. Raises an ArgumentError if the option does not exist.
[ "Set", "the", "value", "for", "an", "option", ".", "Raises", "an", "ArgumentError", "if", "the", "option", "does", "not", "exist", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/result.rb#L36-L42
train
leejarvis/slop
lib/slop/result.rb
Slop.Result.option
def option(flag) options.find do |o| o.flags.any? { |f| clean_key(f) == clean_key(flag) } end end
ruby
def option(flag) options.find do |o| o.flags.any? { |f| clean_key(f) == clean_key(flag) } end end
[ "def", "option", "(", "flag", ")", "options", ".", "find", "do", "|", "o", "|", "o", ".", "flags", ".", "any?", "{", "|", "f", "|", "clean_key", "(", "f", ")", "==", "clean_key", "(", "flag", ")", "}", "end", "end" ]
Returns an Option if it exists. Ignores any prefixed hyphens.
[ "Returns", "an", "Option", "if", "it", "exists", ".", "Ignores", "any", "prefixed", "hyphens", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/result.rb#L46-L50
train
leejarvis/slop
lib/slop/result.rb
Slop.Result.to_hash
def to_hash Hash[options.reject(&:null?).map { |o| [o.key, o.value] }] end
ruby
def to_hash Hash[options.reject(&:null?).map { |o| [o.key, o.value] }] end
[ "def", "to_hash", "Hash", "[", "options", ".", "reject", "(", ":null?", ")", ".", "map", "{", "|", "o", "|", "[", "o", ".", "key", ",", "o", ".", "value", "]", "}", "]", "end" ]
Returns a hash with option key => value.
[ "Returns", "a", "hash", "with", "option", "key", "=", ">", "value", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/result.rb#L91-L93
train
leejarvis/slop
lib/slop/parser.rb
Slop.Parser.try_process
def try_process(flag, arg) if option = matching_option(flag) process(option, arg) elsif flag.start_with?("--no-") && option = matching_option(flag.sub("no-", "")) process(option, false) elsif flag =~ /\A-[^-]{2,}/ try_process_smashed_arg(flag) || try_process_grouped_flags(flag, arg) else if flag.start_with?("-") && !suppress_errors? raise UnknownOption.new("unknown option `#{flag}'", "#{flag}") end end end
ruby
def try_process(flag, arg) if option = matching_option(flag) process(option, arg) elsif flag.start_with?("--no-") && option = matching_option(flag.sub("no-", "")) process(option, false) elsif flag =~ /\A-[^-]{2,}/ try_process_smashed_arg(flag) || try_process_grouped_flags(flag, arg) else if flag.start_with?("-") && !suppress_errors? raise UnknownOption.new("unknown option `#{flag}'", "#{flag}") end end end
[ "def", "try_process", "(", "flag", ",", "arg", ")", "if", "option", "=", "matching_option", "(", "flag", ")", "process", "(", "option", ",", "arg", ")", "elsif", "flag", ".", "start_with?", "(", "\"--no-\"", ")", "&&", "option", "=", "matching_option", "(", "flag", ".", "sub", "(", "\"no-\"", ",", "\"\"", ")", ")", "process", "(", "option", ",", "false", ")", "elsif", "flag", "=~", "/", "\\A", "/", "try_process_smashed_arg", "(", "flag", ")", "||", "try_process_grouped_flags", "(", "flag", ",", "arg", ")", "else", "if", "flag", ".", "start_with?", "(", "\"-\"", ")", "&&", "!", "suppress_errors?", "raise", "UnknownOption", ".", "new", "(", "\"unknown option `#{flag}'\"", ",", "\"#{flag}\"", ")", "end", "end", "end" ]
Try and find an option to process
[ "Try", "and", "find", "an", "option", "to", "process" ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/parser.rb#L116-L128
train
leejarvis/slop
lib/slop/option.rb
Slop.Option.key
def key key = config[:key] || flags.last.sub(/\A--?/, '') key = key.tr '-', '_' if underscore_flags? key.to_sym end
ruby
def key key = config[:key] || flags.last.sub(/\A--?/, '') key = key.tr '-', '_' if underscore_flags? key.to_sym end
[ "def", "key", "key", "=", "config", "[", ":key", "]", "||", "flags", ".", "last", ".", "sub", "(", "/", "\\A", "/", ",", "''", ")", "key", "=", "key", ".", "tr", "'-'", ",", "'_'", "if", "underscore_flags?", "key", ".", "to_sym", "end" ]
Returns the last key as a symbol. Used in Options.to_hash.
[ "Returns", "the", "last", "key", "as", "a", "symbol", ".", "Used", "in", "Options", ".", "to_hash", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/option.rb#L116-L120
train
leejarvis/slop
lib/slop/options.rb
Slop.Options.separator
def separator(string = "") if separators[options.size] separators[-1] += "\n#{string}" else separators[options.size] = string end end
ruby
def separator(string = "") if separators[options.size] separators[-1] += "\n#{string}" else separators[options.size] = string end end
[ "def", "separator", "(", "string", "=", "\"\"", ")", "if", "separators", "[", "options", ".", "size", "]", "separators", "[", "-", "1", "]", "+=", "\"\\n#{string}\"", "else", "separators", "[", "options", ".", "size", "]", "=", "string", "end", "end" ]
Add a separator between options. Used when displaying the help text.
[ "Add", "a", "separator", "between", "options", ".", "Used", "when", "displaying", "the", "help", "text", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/options.rb#L62-L68
train
leejarvis/slop
lib/slop/options.rb
Slop.Options.method_missing
def method_missing(name, *args, **config, &block) if respond_to_missing?(name) config[:type] = name on(*args, config, &block) else super end end
ruby
def method_missing(name, *args, **config, &block) if respond_to_missing?(name) config[:type] = name on(*args, config, &block) else super end end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "**", "config", ",", "&", "block", ")", "if", "respond_to_missing?", "(", "name", ")", "config", "[", ":type", "]", "=", "name", "on", "(", "args", ",", "config", ",", "block", ")", "else", "super", "end", "end" ]
Handle custom option types. Will fall back to raising an exception if an option is not defined.
[ "Handle", "custom", "option", "types", ".", "Will", "fall", "back", "to", "raising", "an", "exception", "if", "an", "option", "is", "not", "defined", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/options.rb#L82-L89
train
guard/guard-rspec
lib/guard/rspec_formatter.rb
Guard.RSpecFormatter.write_summary
def write_summary(duration, total, failures, pending) _write do |f| f.puts _message(total, failures, pending, duration) f.puts _failed_paths.join("\n") if failures > 0 end end
ruby
def write_summary(duration, total, failures, pending) _write do |f| f.puts _message(total, failures, pending, duration) f.puts _failed_paths.join("\n") if failures > 0 end end
[ "def", "write_summary", "(", "duration", ",", "total", ",", "failures", ",", "pending", ")", "_write", "do", "|", "f", "|", "f", ".", "puts", "_message", "(", "total", ",", "failures", ",", "pending", ",", "duration", ")", "f", ".", "puts", "_failed_paths", ".", "join", "(", "\"\\n\"", ")", "if", "failures", ">", "0", "end", "end" ]
Write summary to temporary file for runner
[ "Write", "summary", "to", "temporary", "file", "for", "runner" ]
1cf25c7127112c246b6e1a38208c32a6aee8a6c7
https://github.com/guard/guard-rspec/blob/1cf25c7127112c246b6e1a38208c32a6aee8a6c7/lib/guard/rspec_formatter.rb#L109-L114
train
nixme/pry-nav
lib/pry-nav/pry_remote_ext.rb
PryRemote.Server.run
def run if PryNav.current_remote_server raise 'Already running a pry-remote session!' else PryNav.current_remote_server = self end setup Pry.start @object, { :input => client.input_proxy, :output => client.output, :pry_remote => true } end
ruby
def run if PryNav.current_remote_server raise 'Already running a pry-remote session!' else PryNav.current_remote_server = self end setup Pry.start @object, { :input => client.input_proxy, :output => client.output, :pry_remote => true } end
[ "def", "run", "if", "PryNav", ".", "current_remote_server", "raise", "'Already running a pry-remote session!'", "else", "PryNav", ".", "current_remote_server", "=", "self", "end", "setup", "Pry", ".", "start", "@object", ",", "{", ":input", "=>", "client", ".", "input_proxy", ",", ":output", "=>", "client", ".", "output", ",", ":pry_remote", "=>", "true", "}", "end" ]
Override the call to Pry.start to save off current Server, pass a pry_remote flag so pry-nav knows this is a remote session, and not kill the server right away
[ "Override", "the", "call", "to", "Pry", ".", "start", "to", "save", "off", "current", "Server", "pass", "a", "pry_remote", "flag", "so", "pry", "-", "nav", "knows", "this", "is", "a", "remote", "session", "and", "not", "kill", "the", "server", "right", "away" ]
56139f68fec5d89427147606adf9d819c3dee94c
https://github.com/nixme/pry-nav/blob/56139f68fec5d89427147606adf9d819c3dee94c/lib/pry-nav/pry_remote_ext.rb#L9-L22
train
pluginaweek/state_machine
lib/state_machine/transition.rb
StateMachine.Transition.pausable
def pausable begin halted = !catch(:halt) { yield; true } rescue Exception => error raise unless @resume_block end if @resume_block @resume_block.call(halted, error) else halted end end
ruby
def pausable begin halted = !catch(:halt) { yield; true } rescue Exception => error raise unless @resume_block end if @resume_block @resume_block.call(halted, error) else halted end end
[ "def", "pausable", "begin", "halted", "=", "!", "catch", "(", ":halt", ")", "{", "yield", ";", "true", "}", "rescue", "Exception", "=>", "error", "raise", "unless", "@resume_block", "end", "if", "@resume_block", "@resume_block", ".", "call", "(", "halted", ",", "error", ")", "else", "halted", "end", "end" ]
Runs a block that may get paused. If the block doesn't pause, then execution will continue as normal. If the block gets paused, then it will take care of switching the execution context when it's resumed. This will return true if the given block halts for a reason other than getting paused.
[ "Runs", "a", "block", "that", "may", "get", "paused", ".", "If", "the", "block", "doesn", "t", "pause", "then", "execution", "will", "continue", "as", "normal", ".", "If", "the", "block", "gets", "paused", "then", "it", "will", "take", "care", "of", "switching", "the", "execution", "context", "when", "it", "s", "resumed", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/transition.rb#L346-L358
train
pluginaweek/state_machine
lib/state_machine/event.rb
StateMachine.Event.transition
def transition(options) raise ArgumentError, 'Must specify as least one transition requirement' if options.empty? # Only a certain subset of explicit options are allowed for transition # requirements assert_valid_keys(options, :from, :to, :except_from, :except_to, :if, :unless) if (options.keys - [:from, :to, :on, :except_from, :except_to, :except_on, :if, :unless]).empty? branches << branch = Branch.new(options.merge(:on => name)) @known_states |= branch.known_states branch end
ruby
def transition(options) raise ArgumentError, 'Must specify as least one transition requirement' if options.empty? # Only a certain subset of explicit options are allowed for transition # requirements assert_valid_keys(options, :from, :to, :except_from, :except_to, :if, :unless) if (options.keys - [:from, :to, :on, :except_from, :except_to, :except_on, :if, :unless]).empty? branches << branch = Branch.new(options.merge(:on => name)) @known_states |= branch.known_states branch end
[ "def", "transition", "(", "options", ")", "raise", "ArgumentError", ",", "'Must specify as least one transition requirement'", "if", "options", ".", "empty?", "# Only a certain subset of explicit options are allowed for transition", "# requirements", "assert_valid_keys", "(", "options", ",", ":from", ",", ":to", ",", ":except_from", ",", ":except_to", ",", ":if", ",", ":unless", ")", "if", "(", "options", ".", "keys", "-", "[", ":from", ",", ":to", ",", ":on", ",", ":except_from", ",", ":except_to", ",", ":except_on", ",", ":if", ",", ":unless", "]", ")", ".", "empty?", "branches", "<<", "branch", "=", "Branch", ".", "new", "(", "options", ".", "merge", "(", ":on", "=>", "name", ")", ")", "@known_states", "|=", "branch", ".", "known_states", "branch", "end" ]
Creates a new transition that determines what to change the current state to when this event fires. Since this transition is being defined within an event context, you do *not* need to specify the <tt>:on</tt> option for the transition. For example: state_machine do event :ignite do transition :parked => :idling, :idling => same, :if => :seatbelt_on? # Transitions to :idling if seatbelt is on transition all => :parked, :unless => :seatbelt_on? # Transitions to :parked if seatbelt is off end end See StateMachine::Machine#transition for a description of the possible configurations for defining transitions.
[ "Creates", "a", "new", "transition", "that", "determines", "what", "to", "change", "the", "current", "state", "to", "when", "this", "event", "fires", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/event.rb#L105-L115
train
pluginaweek/state_machine
lib/state_machine/state_context.rb
StateMachine.StateContext.transition
def transition(options) assert_valid_keys(options, :from, :to, :on, :if, :unless) raise ArgumentError, 'Must specify :on event' unless options[:on] raise ArgumentError, 'Must specify either :to or :from state' unless !options[:to] ^ !options[:from] machine.transition(options.merge(options[:to] ? {:from => state.name} : {:to => state.name})) end
ruby
def transition(options) assert_valid_keys(options, :from, :to, :on, :if, :unless) raise ArgumentError, 'Must specify :on event' unless options[:on] raise ArgumentError, 'Must specify either :to or :from state' unless !options[:to] ^ !options[:from] machine.transition(options.merge(options[:to] ? {:from => state.name} : {:to => state.name})) end
[ "def", "transition", "(", "options", ")", "assert_valid_keys", "(", "options", ",", ":from", ",", ":to", ",", ":on", ",", ":if", ",", ":unless", ")", "raise", "ArgumentError", ",", "'Must specify :on event'", "unless", "options", "[", ":on", "]", "raise", "ArgumentError", ",", "'Must specify either :to or :from state'", "unless", "!", "options", "[", ":to", "]", "^", "!", "options", "[", ":from", "]", "machine", ".", "transition", "(", "options", ".", "merge", "(", "options", "[", ":to", "]", "?", "{", ":from", "=>", "state", ".", "name", "}", ":", "{", ":to", "=>", "state", ".", "name", "}", ")", ")", "end" ]
Creates a new context for the given state Creates a new transition that determines what to change the current state to when an event fires from this state. Since this transition is being defined within a state context, you do *not* need to specify the <tt>:from</tt> option for the transition. For example: state_machine do state :parked do transition :to => :idling, :on => [:ignite, :shift_up] # Transitions to :idling transition :from => [:idling, :parked], :on => :park, :unless => :seatbelt_on? # Transitions to :parked if seatbelt is off end end See StateMachine::Machine#transition for a description of the possible configurations for defining transitions.
[ "Creates", "a", "new", "context", "for", "the", "given", "state", "Creates", "a", "new", "transition", "that", "determines", "what", "to", "change", "the", "current", "state", "to", "when", "an", "event", "fires", "from", "this", "state", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/state_context.rb#L95-L101
train
pluginaweek/state_machine
lib/state_machine/node_collection.rb
StateMachine.NodeCollection.initialize_copy
def initialize_copy(orig) #:nodoc: super nodes = @nodes contexts = @contexts @nodes = [] @contexts = [] @indices = @indices.inject({}) {|indices, (name, *)| indices[name] = {}; indices} # Add nodes *prior* to copying over the contexts so that they don't get # evaluated multiple times concat(nodes.map {|n| n.dup}) @contexts = contexts.dup end
ruby
def initialize_copy(orig) #:nodoc: super nodes = @nodes contexts = @contexts @nodes = [] @contexts = [] @indices = @indices.inject({}) {|indices, (name, *)| indices[name] = {}; indices} # Add nodes *prior* to copying over the contexts so that they don't get # evaluated multiple times concat(nodes.map {|n| n.dup}) @contexts = contexts.dup end
[ "def", "initialize_copy", "(", "orig", ")", "#:nodoc:", "super", "nodes", "=", "@nodes", "contexts", "=", "@contexts", "@nodes", "=", "[", "]", "@contexts", "=", "[", "]", "@indices", "=", "@indices", ".", "inject", "(", "{", "}", ")", "{", "|", "indices", ",", "(", "name", ",", "*", ")", "|", "indices", "[", "name", "]", "=", "{", "}", ";", "indices", "}", "# Add nodes *prior* to copying over the contexts so that they don't get", "# evaluated multiple times", "concat", "(", "nodes", ".", "map", "{", "|", "n", "|", "n", ".", "dup", "}", ")", "@contexts", "=", "contexts", ".", "dup", "end" ]
Creates a new collection of nodes for the given state machine. By default, the collection is empty. Configuration options: * <tt>:index</tt> - One or more attributes to automatically generate hashed indices for in order to perform quick lookups. Default is to index by the :name attribute Creates a copy of this collection such that modifications don't affect the original collection
[ "Creates", "a", "new", "collection", "of", "nodes", "for", "the", "given", "state", "machine", ".", "By", "default", "the", "collection", "is", "empty", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/node_collection.rb#L40-L53
train
pluginaweek/state_machine
lib/state_machine/node_collection.rb
StateMachine.NodeCollection.context
def context(nodes, &block) nodes = nodes.first.is_a?(Matcher) ? nodes.first : WhitelistMatcher.new(nodes) @contexts << context = {:nodes => nodes, :block => block} # Evaluate the new context for existing nodes each {|node| eval_context(context, node)} context end
ruby
def context(nodes, &block) nodes = nodes.first.is_a?(Matcher) ? nodes.first : WhitelistMatcher.new(nodes) @contexts << context = {:nodes => nodes, :block => block} # Evaluate the new context for existing nodes each {|node| eval_context(context, node)} context end
[ "def", "context", "(", "nodes", ",", "&", "block", ")", "nodes", "=", "nodes", ".", "first", ".", "is_a?", "(", "Matcher", ")", "?", "nodes", ".", "first", ":", "WhitelistMatcher", ".", "new", "(", "nodes", ")", "@contexts", "<<", "context", "=", "{", ":nodes", "=>", "nodes", ",", ":block", "=>", "block", "}", "# Evaluate the new context for existing nodes", "each", "{", "|", "node", "|", "eval_context", "(", "context", ",", "node", ")", "}", "context", "end" ]
Tracks a context that should be evaluated for any nodes that get added which match the given set of nodes. Matchers can be used so that the context can get added once and evaluated after multiple adds.
[ "Tracks", "a", "context", "that", "should", "be", "evaluated", "for", "any", "nodes", "that", "get", "added", "which", "match", "the", "given", "set", "of", "nodes", ".", "Matchers", "can", "be", "used", "so", "that", "the", "context", "can", "get", "added", "once", "and", "evaluated", "after", "multiple", "adds", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/node_collection.rb#L75-L83
train
pluginaweek/state_machine
lib/state_machine/machine.rb
StateMachine.Machine.owner_class=
def owner_class=(klass) @owner_class = klass # Create modules for extending the class with state/event-specific methods @helper_modules = helper_modules = {:instance => HelperModule.new(self, :instance), :class => HelperModule.new(self, :class)} owner_class.class_eval do extend helper_modules[:class] include helper_modules[:instance] end # Add class-/instance-level methods to the owner class for state initialization unless owner_class < StateMachine::InstanceMethods owner_class.class_eval do extend StateMachine::ClassMethods include StateMachine::InstanceMethods end define_state_initializer if @initialize_state end # Record this machine as matched to the name in the current owner class. # This will override any machines mapped to the same name in any superclasses. owner_class.state_machines[name] = self end
ruby
def owner_class=(klass) @owner_class = klass # Create modules for extending the class with state/event-specific methods @helper_modules = helper_modules = {:instance => HelperModule.new(self, :instance), :class => HelperModule.new(self, :class)} owner_class.class_eval do extend helper_modules[:class] include helper_modules[:instance] end # Add class-/instance-level methods to the owner class for state initialization unless owner_class < StateMachine::InstanceMethods owner_class.class_eval do extend StateMachine::ClassMethods include StateMachine::InstanceMethods end define_state_initializer if @initialize_state end # Record this machine as matched to the name in the current owner class. # This will override any machines mapped to the same name in any superclasses. owner_class.state_machines[name] = self end
[ "def", "owner_class", "=", "(", "klass", ")", "@owner_class", "=", "klass", "# Create modules for extending the class with state/event-specific methods", "@helper_modules", "=", "helper_modules", "=", "{", ":instance", "=>", "HelperModule", ".", "new", "(", "self", ",", ":instance", ")", ",", ":class", "=>", "HelperModule", ".", "new", "(", "self", ",", ":class", ")", "}", "owner_class", ".", "class_eval", "do", "extend", "helper_modules", "[", ":class", "]", "include", "helper_modules", "[", ":instance", "]", "end", "# Add class-/instance-level methods to the owner class for state initialization", "unless", "owner_class", "<", "StateMachine", "::", "InstanceMethods", "owner_class", ".", "class_eval", "do", "extend", "StateMachine", "::", "ClassMethods", "include", "StateMachine", "::", "InstanceMethods", "end", "define_state_initializer", "if", "@initialize_state", "end", "# Record this machine as matched to the name in the current owner class.", "# This will override any machines mapped to the same name in any superclasses.", "owner_class", ".", "state_machines", "[", "name", "]", "=", "self", "end" ]
Sets the class which is the owner of this state machine. Any methods generated by states, events, or other parts of the machine will be defined on the given owner class.
[ "Sets", "the", "class", "which", "is", "the", "owner", "of", "this", "state", "machine", ".", "Any", "methods", "generated", "by", "states", "events", "or", "other", "parts", "of", "the", "machine", "will", "be", "defined", "on", "the", "given", "owner", "class", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/machine.rb#L601-L624
train
pluginaweek/state_machine
lib/state_machine/callback.rb
StateMachine.Callback.run_methods
def run_methods(object, context = {}, index = 0, *args, &block) if type == :around if current_method = @methods[index] yielded = false evaluate_method(object, current_method, *args) do yielded = true run_methods(object, context, index + 1, *args, &block) end throw :halt unless yielded else yield if block_given? end else @methods.each do |method| result = evaluate_method(object, method, *args) throw :halt if @terminator && @terminator.call(result) end end end
ruby
def run_methods(object, context = {}, index = 0, *args, &block) if type == :around if current_method = @methods[index] yielded = false evaluate_method(object, current_method, *args) do yielded = true run_methods(object, context, index + 1, *args, &block) end throw :halt unless yielded else yield if block_given? end else @methods.each do |method| result = evaluate_method(object, method, *args) throw :halt if @terminator && @terminator.call(result) end end end
[ "def", "run_methods", "(", "object", ",", "context", "=", "{", "}", ",", "index", "=", "0", ",", "*", "args", ",", "&", "block", ")", "if", "type", "==", ":around", "if", "current_method", "=", "@methods", "[", "index", "]", "yielded", "=", "false", "evaluate_method", "(", "object", ",", "current_method", ",", "args", ")", "do", "yielded", "=", "true", "run_methods", "(", "object", ",", "context", ",", "index", "+", "1", ",", "args", ",", "block", ")", "end", "throw", ":halt", "unless", "yielded", "else", "yield", "if", "block_given?", "end", "else", "@methods", ".", "each", "do", "|", "method", "|", "result", "=", "evaluate_method", "(", "object", ",", "method", ",", "args", ")", "throw", ":halt", "if", "@terminator", "&&", "@terminator", ".", "call", "(", "result", ")", "end", "end", "end" ]
Runs all of the methods configured for this callback. When running +around+ callbacks, this will evaluate each method and yield when the last method has yielded. The callback will only halt if one of the methods does not yield. For all other types of callbacks, this will evaluate each method in order. The callback will only halt if the resulting value from the method passes the terminator.
[ "Runs", "all", "of", "the", "methods", "configured", "for", "this", "callback", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/callback.rb#L176-L195
train
teampoltergeist/poltergeist
lib/capybara/poltergeist/web_socket_server.rb
Capybara::Poltergeist.WebSocketServer.accept
def accept @socket = server.accept @messages = {} @driver = ::WebSocket::Driver.server(self) @driver.on(:connect) { |_event| @driver.start } @driver.on(:message) do |event| command_id = JSON.parse(event.data)['command_id'] @messages[command_id] = event.data end end
ruby
def accept @socket = server.accept @messages = {} @driver = ::WebSocket::Driver.server(self) @driver.on(:connect) { |_event| @driver.start } @driver.on(:message) do |event| command_id = JSON.parse(event.data)['command_id'] @messages[command_id] = event.data end end
[ "def", "accept", "@socket", "=", "server", ".", "accept", "@messages", "=", "{", "}", "@driver", "=", "::", "WebSocket", "::", "Driver", ".", "server", "(", "self", ")", "@driver", ".", "on", "(", ":connect", ")", "{", "|", "_event", "|", "@driver", ".", "start", "}", "@driver", ".", "on", "(", ":message", ")", "do", "|", "event", "|", "command_id", "=", "JSON", ".", "parse", "(", "event", ".", "data", ")", "[", "'command_id'", "]", "@messages", "[", "command_id", "]", "=", "event", ".", "data", "end", "end" ]
Accept a client on the TCP server socket, then receive its initial HTTP request and use that to initialize a Web Socket.
[ "Accept", "a", "client", "on", "the", "TCP", "server", "socket", "then", "receive", "its", "initial", "HTTP", "request", "and", "use", "that", "to", "initialize", "a", "Web", "Socket", "." ]
6a27b00407b7845d2b19d4ec1a1e269c207f8957
https://github.com/teampoltergeist/poltergeist/blob/6a27b00407b7845d2b19d4ec1a1e269c207f8957/lib/capybara/poltergeist/web_socket_server.rb#L53-L63
train
teampoltergeist/poltergeist
lib/capybara/poltergeist/web_socket_server.rb
Capybara::Poltergeist.WebSocketServer.send
def send(cmd_id, message, accept_timeout = nil) accept unless connected? driver.text(message) receive(cmd_id, accept_timeout) rescue Errno::EWOULDBLOCK raise TimeoutError, message end
ruby
def send(cmd_id, message, accept_timeout = nil) accept unless connected? driver.text(message) receive(cmd_id, accept_timeout) rescue Errno::EWOULDBLOCK raise TimeoutError, message end
[ "def", "send", "(", "cmd_id", ",", "message", ",", "accept_timeout", "=", "nil", ")", "accept", "unless", "connected?", "driver", ".", "text", "(", "message", ")", "receive", "(", "cmd_id", ",", "accept_timeout", ")", "rescue", "Errno", "::", "EWOULDBLOCK", "raise", "TimeoutError", ",", "message", "end" ]
Send a message and block until there is a response
[ "Send", "a", "message", "and", "block", "until", "there", "is", "a", "response" ]
6a27b00407b7845d2b19d4ec1a1e269c207f8957
https://github.com/teampoltergeist/poltergeist/blob/6a27b00407b7845d2b19d4ec1a1e269c207f8957/lib/capybara/poltergeist/web_socket_server.rb#L94-L100
train
makandra/active_type
lib/active_type/util.rb
ActiveType.Util.using_single_table_inheritance?
def using_single_table_inheritance?(klass, record) inheritance_column = klass.inheritance_column record[inheritance_column].present? && record.has_attribute?(inheritance_column) end
ruby
def using_single_table_inheritance?(klass, record) inheritance_column = klass.inheritance_column record[inheritance_column].present? && record.has_attribute?(inheritance_column) end
[ "def", "using_single_table_inheritance?", "(", "klass", ",", "record", ")", "inheritance_column", "=", "klass", ".", "inheritance_column", "record", "[", "inheritance_column", "]", ".", "present?", "&&", "record", ".", "has_attribute?", "(", "inheritance_column", ")", "end" ]
Backport for Rails 3.2
[ "Backport", "for", "Rails", "3", ".", "2" ]
11212248ab668f4a9ddeef4df79e6029c95c5cee
https://github.com/makandra/active_type/blob/11212248ab668f4a9ddeef4df79e6029c95c5cee/lib/active_type/util.rb#L52-L55
train
chef/cheffish
lib/cheffish/node_properties.rb
Cheffish.NodeProperties.tag
def tag(*tags) attribute "tags" do |existing_tags| existing_tags ||= [] tags.each do |tag| if !existing_tags.include?(tag.to_s) existing_tags << tag.to_s end end existing_tags end end
ruby
def tag(*tags) attribute "tags" do |existing_tags| existing_tags ||= [] tags.each do |tag| if !existing_tags.include?(tag.to_s) existing_tags << tag.to_s end end existing_tags end end
[ "def", "tag", "(", "*", "tags", ")", "attribute", "\"tags\"", "do", "|", "existing_tags", "|", "existing_tags", "||=", "[", "]", "tags", ".", "each", "do", "|", "tag", "|", "if", "!", "existing_tags", ".", "include?", "(", "tag", ".", "to_s", ")", "existing_tags", "<<", "tag", ".", "to_s", "end", "end", "existing_tags", "end", "end" ]
Patchy tags tag 'webserver', 'apache', 'myenvironment'
[ "Patchy", "tags", "tag", "webserver", "apache", "myenvironment" ]
00e4475208c67d3578b83c2c987322e5fa70ec0f
https://github.com/chef/cheffish/blob/00e4475208c67d3578b83c2c987322e5fa70ec0f/lib/cheffish/node_properties.rb#L38-L48
train
jamesmartin/inline_svg
lib/inline_svg/transform_pipeline/transformations/transformation.rb
InlineSvg::TransformPipeline::Transformations.Transformation.with_svg
def with_svg(doc) doc = Nokogiri::XML::Document.parse( doc.to_html(encoding: "UTF-8"), nil, "UTF-8" ) svg = doc.at_css "svg" yield svg if svg && block_given? doc end
ruby
def with_svg(doc) doc = Nokogiri::XML::Document.parse( doc.to_html(encoding: "UTF-8"), nil, "UTF-8" ) svg = doc.at_css "svg" yield svg if svg && block_given? doc end
[ "def", "with_svg", "(", "doc", ")", "doc", "=", "Nokogiri", "::", "XML", "::", "Document", ".", "parse", "(", "doc", ".", "to_html", "(", "encoding", ":", "\"UTF-8\"", ")", ",", "nil", ",", "\"UTF-8\"", ")", "svg", "=", "doc", ".", "at_css", "\"svg\"", "yield", "svg", "if", "svg", "&&", "block_given?", "doc", "end" ]
Parses a document and yields the contained SVG nodeset to the given block if it exists. Returns a Nokogiri::XML::Document.
[ "Parses", "a", "document", "and", "yields", "the", "contained", "SVG", "nodeset", "to", "the", "given", "block", "if", "it", "exists", "." ]
9cdc503632eae4b7e44e9502c5af79e8f9aa85d2
https://github.com/jamesmartin/inline_svg/blob/9cdc503632eae4b7e44e9502c5af79e8f9aa85d2/lib/inline_svg/transform_pipeline/transformations/transformation.rb#L21-L28
train
jamesmartin/inline_svg
lib/inline_svg/cached_asset_file.rb
InlineSvg.CachedAssetFile.named
def named(asset_name) assets[key_for_asset(asset_name)] or raise InlineSvg::AssetFile::FileNotFound.new("Asset not found: #{asset_name}") end
ruby
def named(asset_name) assets[key_for_asset(asset_name)] or raise InlineSvg::AssetFile::FileNotFound.new("Asset not found: #{asset_name}") end
[ "def", "named", "(", "asset_name", ")", "assets", "[", "key_for_asset", "(", "asset_name", ")", "]", "or", "raise", "InlineSvg", "::", "AssetFile", "::", "FileNotFound", ".", "new", "(", "\"Asset not found: #{asset_name}\"", ")", "end" ]
For each of the given paths, recursively reads each asset and stores its contents alongside the full path to the asset. paths - One or more String representing directories on disk to search for asset files. Note: paths are searched recursively. filters - One or more Strings/Regexps to match assets against. Only assets matching all filters will be cached and available to load. Note: Specifying no filters will cache every file found in paths. Public: Finds the named asset and returns the contents as a string. asset_name - A string representing the name of the asset to load Returns: A String or raises InlineSvg::AssetFile::FileNotFound error
[ "For", "each", "of", "the", "given", "paths", "recursively", "reads", "each", "asset", "and", "stores", "its", "contents", "alongside", "the", "full", "path", "to", "the", "asset", "." ]
9cdc503632eae4b7e44e9502c5af79e8f9aa85d2
https://github.com/jamesmartin/inline_svg/blob/9cdc503632eae4b7e44e9502c5af79e8f9aa85d2/lib/inline_svg/cached_asset_file.rb#L28-L31
train
yob/pdf-reader
lib/pdf/reader.rb
PDF.Reader.doc_strings_to_utf8
def doc_strings_to_utf8(obj) case obj when ::Hash then {}.tap { |new_hash| obj.each do |key, value| new_hash[key] = doc_strings_to_utf8(value) end } when Array then obj.map { |item| doc_strings_to_utf8(item) } when String then if obj[0,2].unpack("C*") == [254, 255] utf16_to_utf8(obj) else pdfdoc_to_utf8(obj) end else @objects.deref(obj) end end
ruby
def doc_strings_to_utf8(obj) case obj when ::Hash then {}.tap { |new_hash| obj.each do |key, value| new_hash[key] = doc_strings_to_utf8(value) end } when Array then obj.map { |item| doc_strings_to_utf8(item) } when String then if obj[0,2].unpack("C*") == [254, 255] utf16_to_utf8(obj) else pdfdoc_to_utf8(obj) end else @objects.deref(obj) end end
[ "def", "doc_strings_to_utf8", "(", "obj", ")", "case", "obj", "when", "::", "Hash", "then", "{", "}", ".", "tap", "{", "|", "new_hash", "|", "obj", ".", "each", "do", "|", "key", ",", "value", "|", "new_hash", "[", "key", "]", "=", "doc_strings_to_utf8", "(", "value", ")", "end", "}", "when", "Array", "then", "obj", ".", "map", "{", "|", "item", "|", "doc_strings_to_utf8", "(", "item", ")", "}", "when", "String", "then", "if", "obj", "[", "0", ",", "2", "]", ".", "unpack", "(", "\"C*\"", ")", "==", "[", "254", ",", "255", "]", "utf16_to_utf8", "(", "obj", ")", "else", "pdfdoc_to_utf8", "(", "obj", ")", "end", "else", "@objects", ".", "deref", "(", "obj", ")", "end", "end" ]
recursively convert strings from outside a content stream into UTF-8
[ "recursively", "convert", "strings", "from", "outside", "a", "content", "stream", "into", "UTF", "-", "8" ]
2f91e4912c2ddd2d1ca447c2d1df9623fb833601
https://github.com/yob/pdf-reader/blob/2f91e4912c2ddd2d1ca447c2d1df9623fb833601/lib/pdf/reader.rb#L213-L232
train
yob/pdf-reader
examples/extract_images.rb
ExtractImages.Tiff.save_group_four
def save_group_four(filename) k = stream.hash[:DecodeParms][:K] h = stream.hash[:Height] w = stream.hash[:Width] bpc = stream.hash[:BitsPerComponent] mask = stream.hash[:ImageMask] len = stream.hash[:Length] cols = stream.hash[:DecodeParms][:Columns] puts "#{filename}: h=#{h}, w=#{w}, bpc=#{bpc}, mask=#{mask}, len=#{len}, cols=#{cols}, k=#{k}" # Synthesize a TIFF header long_tag = lambda {|tag, value| [ tag, 4, 1, value ].pack( "ssII" ) } short_tag = lambda {|tag, value| [ tag, 3, 1, value ].pack( "ssII" ) } # header = byte order, version magic, offset of directory, directory count, # followed by a series of tags containing metadata: 259 is a magic number for # the compression type; 273 is the offset of the image data. tiff = [ 73, 73, 42, 8, 5 ].pack("ccsIs") \ + short_tag.call( 256, cols ) \ + short_tag.call( 257, h ) \ + short_tag.call( 259, 4 ) \ + long_tag.call( 273, (10 + (5*12) + 4) ) \ + long_tag.call( 279, len) \ + [0].pack("I") \ + stream.data File.open(filename, "wb") { |file| file.write tiff } end
ruby
def save_group_four(filename) k = stream.hash[:DecodeParms][:K] h = stream.hash[:Height] w = stream.hash[:Width] bpc = stream.hash[:BitsPerComponent] mask = stream.hash[:ImageMask] len = stream.hash[:Length] cols = stream.hash[:DecodeParms][:Columns] puts "#{filename}: h=#{h}, w=#{w}, bpc=#{bpc}, mask=#{mask}, len=#{len}, cols=#{cols}, k=#{k}" # Synthesize a TIFF header long_tag = lambda {|tag, value| [ tag, 4, 1, value ].pack( "ssII" ) } short_tag = lambda {|tag, value| [ tag, 3, 1, value ].pack( "ssII" ) } # header = byte order, version magic, offset of directory, directory count, # followed by a series of tags containing metadata: 259 is a magic number for # the compression type; 273 is the offset of the image data. tiff = [ 73, 73, 42, 8, 5 ].pack("ccsIs") \ + short_tag.call( 256, cols ) \ + short_tag.call( 257, h ) \ + short_tag.call( 259, 4 ) \ + long_tag.call( 273, (10 + (5*12) + 4) ) \ + long_tag.call( 279, len) \ + [0].pack("I") \ + stream.data File.open(filename, "wb") { |file| file.write tiff } end
[ "def", "save_group_four", "(", "filename", ")", "k", "=", "stream", ".", "hash", "[", ":DecodeParms", "]", "[", ":K", "]", "h", "=", "stream", ".", "hash", "[", ":Height", "]", "w", "=", "stream", ".", "hash", "[", ":Width", "]", "bpc", "=", "stream", ".", "hash", "[", ":BitsPerComponent", "]", "mask", "=", "stream", ".", "hash", "[", ":ImageMask", "]", "len", "=", "stream", ".", "hash", "[", ":Length", "]", "cols", "=", "stream", ".", "hash", "[", ":DecodeParms", "]", "[", ":Columns", "]", "puts", "\"#{filename}: h=#{h}, w=#{w}, bpc=#{bpc}, mask=#{mask}, len=#{len}, cols=#{cols}, k=#{k}\"", "# Synthesize a TIFF header", "long_tag", "=", "lambda", "{", "|", "tag", ",", "value", "|", "[", "tag", ",", "4", ",", "1", ",", "value", "]", ".", "pack", "(", "\"ssII\"", ")", "}", "short_tag", "=", "lambda", "{", "|", "tag", ",", "value", "|", "[", "tag", ",", "3", ",", "1", ",", "value", "]", ".", "pack", "(", "\"ssII\"", ")", "}", "# header = byte order, version magic, offset of directory, directory count,", "# followed by a series of tags containing metadata: 259 is a magic number for", "# the compression type; 273 is the offset of the image data.", "tiff", "=", "[", "73", ",", "73", ",", "42", ",", "8", ",", "5", "]", ".", "pack", "(", "\"ccsIs\"", ")", "+", "short_tag", ".", "call", "(", "256", ",", "cols", ")", "+", "short_tag", ".", "call", "(", "257", ",", "h", ")", "+", "short_tag", ".", "call", "(", "259", ",", "4", ")", "+", "long_tag", ".", "call", "(", "273", ",", "(", "10", "+", "(", "5", "*", "12", ")", "+", "4", ")", ")", "+", "long_tag", ".", "call", "(", "279", ",", "len", ")", "+", "[", "0", "]", ".", "pack", "(", "\"I\"", ")", "+", "stream", ".", "data", "File", ".", "open", "(", "filename", ",", "\"wb\"", ")", "{", "|", "file", "|", "file", ".", "write", "tiff", "}", "end" ]
Group 4, 2D
[ "Group", "4", "2D" ]
2f91e4912c2ddd2d1ca447c2d1df9623fb833601
https://github.com/yob/pdf-reader/blob/2f91e4912c2ddd2d1ca447c2d1df9623fb833601/examples/extract_images.rb#L196-L221
train
rails/rails-observers
lib/rails/observers/active_model/observing.rb
ActiveModel.Observer.disabled_for?
def disabled_for?(object) #:nodoc: klass = object.class return false unless klass.respond_to?(:observers) klass.observers.disabled_for?(self) end
ruby
def disabled_for?(object) #:nodoc: klass = object.class return false unless klass.respond_to?(:observers) klass.observers.disabled_for?(self) end
[ "def", "disabled_for?", "(", "object", ")", "#:nodoc:", "klass", "=", "object", ".", "class", "return", "false", "unless", "klass", ".", "respond_to?", "(", ":observers", ")", "klass", ".", "observers", ".", "disabled_for?", "(", "self", ")", "end" ]
Returns true if notifications are disabled for this object.
[ "Returns", "true", "if", "notifications", "are", "disabled", "for", "this", "object", "." ]
25eb685d68e8fcd0675fff33852ee341f7ec2a53
https://github.com/rails/rails-observers/blob/25eb685d68e8fcd0675fff33852ee341f7ec2a53/lib/rails/observers/active_model/observing.rb#L368-L372
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.copy
def copy(from) @scalar = from.scalar @numerator = from.numerator @denominator = from.denominator @base = from.base? @signature = from.signature @base_scalar = from.base_scalar @unit_name = begin from.unit_name rescue nil end self end
ruby
def copy(from) @scalar = from.scalar @numerator = from.numerator @denominator = from.denominator @base = from.base? @signature = from.signature @base_scalar = from.base_scalar @unit_name = begin from.unit_name rescue nil end self end
[ "def", "copy", "(", "from", ")", "@scalar", "=", "from", ".", "scalar", "@numerator", "=", "from", ".", "numerator", "@denominator", "=", "from", ".", "denominator", "@base", "=", "from", ".", "base?", "@signature", "=", "from", ".", "signature", "@base_scalar", "=", "from", ".", "base_scalar", "@unit_name", "=", "begin", "from", ".", "unit_name", "rescue", "nil", "end", "self", "end" ]
Used to copy one unit to another @param [Unit] from Unit to copy definition from @return [Unit]
[ "Used", "to", "copy", "one", "unit", "to", "another" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L430-L443
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.base?
def base? return @base if defined? @base @base = (@numerator + @denominator) .compact .uniq .map { |unit| RubyUnits::Unit.definition(unit) } .all? { |element| element.unity? || element.base? } @base end
ruby
def base? return @base if defined? @base @base = (@numerator + @denominator) .compact .uniq .map { |unit| RubyUnits::Unit.definition(unit) } .all? { |element| element.unity? || element.base? } @base end
[ "def", "base?", "return", "@base", "if", "defined?", "@base", "@base", "=", "(", "@numerator", "+", "@denominator", ")", ".", "compact", ".", "uniq", ".", "map", "{", "|", "unit", "|", "RubyUnits", "::", "Unit", ".", "definition", "(", "unit", ")", "}", ".", "all?", "{", "|", "element", "|", "element", ".", "unity?", "||", "element", ".", "base?", "}", "@base", "end" ]
Is this unit in base form? @return [Boolean]
[ "Is", "this", "unit", "in", "base", "form?" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L563-L571
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.to_base
def to_base return self if base? if @@unit_map[units] =~ /\A<(?:temp|deg)[CRF]>\Z/ @signature = @@kinds.key(:temperature) base = if temperature? convert_to('tempK') elsif degree? convert_to('degK') end return base end cached = (begin (@@base_unit_cache[units] * scalar) rescue nil end) return cached if cached num = [] den = [] q = Rational(1) @numerator.compact.each do |num_unit| if @@prefix_values[num_unit] q *= @@prefix_values[num_unit] else q *= @@unit_values[num_unit][:scalar] if @@unit_values[num_unit] num << @@unit_values[num_unit][:numerator] if @@unit_values[num_unit] && @@unit_values[num_unit][:numerator] den << @@unit_values[num_unit][:denominator] if @@unit_values[num_unit] && @@unit_values[num_unit][:denominator] end end @denominator.compact.each do |num_unit| if @@prefix_values[num_unit] q /= @@prefix_values[num_unit] else q /= @@unit_values[num_unit][:scalar] if @@unit_values[num_unit] den << @@unit_values[num_unit][:numerator] if @@unit_values[num_unit] && @@unit_values[num_unit][:numerator] num << @@unit_values[num_unit][:denominator] if @@unit_values[num_unit] && @@unit_values[num_unit][:denominator] end end num = num.flatten.compact den = den.flatten.compact num = UNITY_ARRAY if num.empty? base = RubyUnits::Unit.new(RubyUnits::Unit.eliminate_terms(q, num, den)) @@base_unit_cache[units] = base base * @scalar end
ruby
def to_base return self if base? if @@unit_map[units] =~ /\A<(?:temp|deg)[CRF]>\Z/ @signature = @@kinds.key(:temperature) base = if temperature? convert_to('tempK') elsif degree? convert_to('degK') end return base end cached = (begin (@@base_unit_cache[units] * scalar) rescue nil end) return cached if cached num = [] den = [] q = Rational(1) @numerator.compact.each do |num_unit| if @@prefix_values[num_unit] q *= @@prefix_values[num_unit] else q *= @@unit_values[num_unit][:scalar] if @@unit_values[num_unit] num << @@unit_values[num_unit][:numerator] if @@unit_values[num_unit] && @@unit_values[num_unit][:numerator] den << @@unit_values[num_unit][:denominator] if @@unit_values[num_unit] && @@unit_values[num_unit][:denominator] end end @denominator.compact.each do |num_unit| if @@prefix_values[num_unit] q /= @@prefix_values[num_unit] else q /= @@unit_values[num_unit][:scalar] if @@unit_values[num_unit] den << @@unit_values[num_unit][:numerator] if @@unit_values[num_unit] && @@unit_values[num_unit][:numerator] num << @@unit_values[num_unit][:denominator] if @@unit_values[num_unit] && @@unit_values[num_unit][:denominator] end end num = num.flatten.compact den = den.flatten.compact num = UNITY_ARRAY if num.empty? base = RubyUnits::Unit.new(RubyUnits::Unit.eliminate_terms(q, num, den)) @@base_unit_cache[units] = base base * @scalar end
[ "def", "to_base", "return", "self", "if", "base?", "if", "@@unit_map", "[", "units", "]", "=~", "/", "\\A", "\\Z", "/", "@signature", "=", "@@kinds", ".", "key", "(", ":temperature", ")", "base", "=", "if", "temperature?", "convert_to", "(", "'tempK'", ")", "elsif", "degree?", "convert_to", "(", "'degK'", ")", "end", "return", "base", "end", "cached", "=", "(", "begin", "(", "@@base_unit_cache", "[", "units", "]", "*", "scalar", ")", "rescue", "nil", "end", ")", "return", "cached", "if", "cached", "num", "=", "[", "]", "den", "=", "[", "]", "q", "=", "Rational", "(", "1", ")", "@numerator", ".", "compact", ".", "each", "do", "|", "num_unit", "|", "if", "@@prefix_values", "[", "num_unit", "]", "q", "*=", "@@prefix_values", "[", "num_unit", "]", "else", "q", "*=", "@@unit_values", "[", "num_unit", "]", "[", ":scalar", "]", "if", "@@unit_values", "[", "num_unit", "]", "num", "<<", "@@unit_values", "[", "num_unit", "]", "[", ":numerator", "]", "if", "@@unit_values", "[", "num_unit", "]", "&&", "@@unit_values", "[", "num_unit", "]", "[", ":numerator", "]", "den", "<<", "@@unit_values", "[", "num_unit", "]", "[", ":denominator", "]", "if", "@@unit_values", "[", "num_unit", "]", "&&", "@@unit_values", "[", "num_unit", "]", "[", ":denominator", "]", "end", "end", "@denominator", ".", "compact", ".", "each", "do", "|", "num_unit", "|", "if", "@@prefix_values", "[", "num_unit", "]", "q", "/=", "@@prefix_values", "[", "num_unit", "]", "else", "q", "/=", "@@unit_values", "[", "num_unit", "]", "[", ":scalar", "]", "if", "@@unit_values", "[", "num_unit", "]", "den", "<<", "@@unit_values", "[", "num_unit", "]", "[", ":numerator", "]", "if", "@@unit_values", "[", "num_unit", "]", "&&", "@@unit_values", "[", "num_unit", "]", "[", ":numerator", "]", "num", "<<", "@@unit_values", "[", "num_unit", "]", "[", ":denominator", "]", "if", "@@unit_values", "[", "num_unit", "]", "&&", "@@unit_values", "[", "num_unit", "]", "[", ":denominator", "]", "end", "end", "num", "=", "num", ".", "flatten", ".", "compact", "den", "=", "den", ".", "flatten", ".", "compact", "num", "=", "UNITY_ARRAY", "if", "num", ".", "empty?", "base", "=", "RubyUnits", "::", "Unit", ".", "new", "(", "RubyUnits", "::", "Unit", ".", "eliminate_terms", "(", "q", ",", "num", ",", "den", ")", ")", "@@base_unit_cache", "[", "units", "]", "=", "base", "base", "*", "@scalar", "end" ]
convert to base SI units results of the conversion are cached so subsequent calls to this will be fast @return [Unit] @todo this is brittle as it depends on the display_name of a unit, which can be changed
[ "convert", "to", "base", "SI", "units", "results", "of", "the", "conversion", "are", "cached", "so", "subsequent", "calls", "to", "this", "will", "be", "fast" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L579-L626
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.to_s
def to_s(target_units = nil) out = @output[target_units] return out if out separator = RubyUnits.configuration.separator case target_units when :ft inches = convert_to('in').scalar.to_int out = "#{(inches / 12).truncate}\'#{(inches % 12).round}\"" when :lbs ounces = convert_to('oz').scalar.to_int out = "#{(ounces / 16).truncate}#{separator}lbs, #{(ounces % 16).round}#{separator}oz" when :stone pounds = convert_to('lbs').scalar.to_int out = "#{(pounds / 14).truncate}#{separator}stone, #{(pounds % 14).round}#{separator}lb" when String out = case target_units.strip when /\A\s*\Z/ # whitespace only '' when /(%[\-+\.\w#]+)\s*(.+)*/ # format string like '%0.2f in' begin if Regexp.last_match(2) # unit specified, need to convert convert_to(Regexp.last_match(2)).to_s(Regexp.last_match(1)) else "#{Regexp.last_match(1) % @scalar}#{separator}#{Regexp.last_match(2) || units}".strip end rescue # parse it like a strftime format string (DateTime.new(0) + self).strftime(target_units) end when /(\S+)/ # unit only 'mm' or '1/mm' convert_to(Regexp.last_match(1)).to_s else raise 'unhandled case' end else out = case @scalar when Complex "#{@scalar}#{separator}#{units}" when Rational "#{@scalar == @scalar.to_i ? @scalar.to_i : @scalar}#{separator}#{units}" else "#{'%g' % @scalar}#{separator}#{units}" end.strip end @output[target_units] = out out end
ruby
def to_s(target_units = nil) out = @output[target_units] return out if out separator = RubyUnits.configuration.separator case target_units when :ft inches = convert_to('in').scalar.to_int out = "#{(inches / 12).truncate}\'#{(inches % 12).round}\"" when :lbs ounces = convert_to('oz').scalar.to_int out = "#{(ounces / 16).truncate}#{separator}lbs, #{(ounces % 16).round}#{separator}oz" when :stone pounds = convert_to('lbs').scalar.to_int out = "#{(pounds / 14).truncate}#{separator}stone, #{(pounds % 14).round}#{separator}lb" when String out = case target_units.strip when /\A\s*\Z/ # whitespace only '' when /(%[\-+\.\w#]+)\s*(.+)*/ # format string like '%0.2f in' begin if Regexp.last_match(2) # unit specified, need to convert convert_to(Regexp.last_match(2)).to_s(Regexp.last_match(1)) else "#{Regexp.last_match(1) % @scalar}#{separator}#{Regexp.last_match(2) || units}".strip end rescue # parse it like a strftime format string (DateTime.new(0) + self).strftime(target_units) end when /(\S+)/ # unit only 'mm' or '1/mm' convert_to(Regexp.last_match(1)).to_s else raise 'unhandled case' end else out = case @scalar when Complex "#{@scalar}#{separator}#{units}" when Rational "#{@scalar == @scalar.to_i ? @scalar.to_i : @scalar}#{separator}#{units}" else "#{'%g' % @scalar}#{separator}#{units}" end.strip end @output[target_units] = out out end
[ "def", "to_s", "(", "target_units", "=", "nil", ")", "out", "=", "@output", "[", "target_units", "]", "return", "out", "if", "out", "separator", "=", "RubyUnits", ".", "configuration", ".", "separator", "case", "target_units", "when", ":ft", "inches", "=", "convert_to", "(", "'in'", ")", ".", "scalar", ".", "to_int", "out", "=", "\"#{(inches / 12).truncate}\\'#{(inches % 12).round}\\\"\"", "when", ":lbs", "ounces", "=", "convert_to", "(", "'oz'", ")", ".", "scalar", ".", "to_int", "out", "=", "\"#{(ounces / 16).truncate}#{separator}lbs, #{(ounces % 16).round}#{separator}oz\"", "when", ":stone", "pounds", "=", "convert_to", "(", "'lbs'", ")", ".", "scalar", ".", "to_int", "out", "=", "\"#{(pounds / 14).truncate}#{separator}stone, #{(pounds % 14).round}#{separator}lb\"", "when", "String", "out", "=", "case", "target_units", ".", "strip", "when", "/", "\\A", "\\s", "\\Z", "/", "# whitespace only", "''", "when", "/", "\\-", "\\.", "\\w", "\\s", "/", "# format string like '%0.2f in'", "begin", "if", "Regexp", ".", "last_match", "(", "2", ")", "# unit specified, need to convert", "convert_to", "(", "Regexp", ".", "last_match", "(", "2", ")", ")", ".", "to_s", "(", "Regexp", ".", "last_match", "(", "1", ")", ")", "else", "\"#{Regexp.last_match(1) % @scalar}#{separator}#{Regexp.last_match(2) || units}\"", ".", "strip", "end", "rescue", "# parse it like a strftime format string", "(", "DateTime", ".", "new", "(", "0", ")", "+", "self", ")", ".", "strftime", "(", "target_units", ")", "end", "when", "/", "\\S", "/", "# unit only 'mm' or '1/mm'", "convert_to", "(", "Regexp", ".", "last_match", "(", "1", ")", ")", ".", "to_s", "else", "raise", "'unhandled case'", "end", "else", "out", "=", "case", "@scalar", "when", "Complex", "\"#{@scalar}#{separator}#{units}\"", "when", "Rational", "\"#{@scalar == @scalar.to_i ? @scalar.to_i : @scalar}#{separator}#{units}\"", "else", "\"#{'%g' % @scalar}#{separator}#{units}\"", "end", ".", "strip", "end", "@output", "[", "target_units", "]", "=", "out", "out", "end" ]
Generate human readable output. If the name of a unit is passed, the unit will first be converted to the target unit before output. some named conversions are available @example unit.to_s(:ft) - outputs in feet and inches (e.g., 6'4") unit.to_s(:lbs) - outputs in pounds and ounces (e.g, 8 lbs, 8 oz) You can also pass a standard format string (i.e., '%0.2f') or a strftime format string. output is cached so subsequent calls for the same format will be fast @note Rational scalars that are equal to an integer will be represented as integers (i.e, 6/1 => 6, 4/2 => 2, etc..) @param [Symbol] target_units @return [String]
[ "Generate", "human", "readable", "output", ".", "If", "the", "name", "of", "a", "unit", "is", "passed", "the", "unit", "will", "first", "be", "converted", "to", "the", "target", "unit", "before", "output", ".", "some", "named", "conversions", "are", "available" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L646-L691
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.=~
def =~(other) case other when Unit signature == other.signature else begin x, y = coerce(other) return x =~ y rescue ArgumentError return false end end end
ruby
def =~(other) case other when Unit signature == other.signature else begin x, y = coerce(other) return x =~ y rescue ArgumentError return false end end end
[ "def", "=~", "(", "other", ")", "case", "other", "when", "Unit", "signature", "==", "other", ".", "signature", "else", "begin", "x", ",", "y", "=", "coerce", "(", "other", ")", "return", "x", "=~", "y", "rescue", "ArgumentError", "return", "false", "end", "end", "end" ]
Compare two Unit objects. Throws an exception if they are not of compatible types. Comparisons are done based on the value of the unit in base SI units. @param [Object] other @return [-1|0|1|nil] @raise [NoMethodError] when other does not define <=> @raise [ArgumentError] when units are not compatible Compare Units for equality this is necessary mostly for Complex units. Complex units do not have a <=> operator so we define this one here so that we can properly check complex units for equality. Units of incompatible types are not equal, except when they are both zero and neither is a temperature Equality checks can be tricky since round off errors may make essentially equivalent units appear to be different. @param [Object] other @return [Boolean] check to see if units are compatible, but not the scalar part this check is done by comparing signatures for performance reasons if passed a string, it will create a unit object with the string and then do the comparison @example this permits a syntax like: unit =~ "mm" @note if you want to do a regexp comparison of the unit string do this ... unit.units =~ /regexp/ @param [Object] other @return [Boolean]
[ "Compare", "two", "Unit", "objects", ".", "Throws", "an", "exception", "if", "they", "are", "not", "of", "compatible", "types", ".", "Comparisons", "are", "done", "based", "on", "the", "value", "of", "the", "unit", "in", "base", "SI", "units", "." ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L787-L799
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.+
def +(other) case other when Unit if zero? other.dup elsif self =~ other raise ArgumentError, 'Cannot add two temperatures' if [self, other].all?(&:temperature?) if [self, other].any?(&:temperature?) if temperature? RubyUnits::Unit.new(scalar: (scalar + other.convert_to(temperature_scale).scalar), numerator: @numerator, denominator: @denominator, signature: @signature) else RubyUnits::Unit.new(scalar: (other.scalar + convert_to(other.temperature_scale).scalar), numerator: other.numerator, denominator: other.denominator, signature: other.signature) end else RubyUnits::Unit.new(scalar: (base_scalar + other.base_scalar), numerator: base.numerator, denominator: base.denominator, signature: @signature).convert_to(self) end else raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" end when Date, Time raise ArgumentError, 'Date and Time objects represent fixed points in time and cannot be added to a Unit' else x, y = coerce(other) y + x end end
ruby
def +(other) case other when Unit if zero? other.dup elsif self =~ other raise ArgumentError, 'Cannot add two temperatures' if [self, other].all?(&:temperature?) if [self, other].any?(&:temperature?) if temperature? RubyUnits::Unit.new(scalar: (scalar + other.convert_to(temperature_scale).scalar), numerator: @numerator, denominator: @denominator, signature: @signature) else RubyUnits::Unit.new(scalar: (other.scalar + convert_to(other.temperature_scale).scalar), numerator: other.numerator, denominator: other.denominator, signature: other.signature) end else RubyUnits::Unit.new(scalar: (base_scalar + other.base_scalar), numerator: base.numerator, denominator: base.denominator, signature: @signature).convert_to(self) end else raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" end when Date, Time raise ArgumentError, 'Date and Time objects represent fixed points in time and cannot be added to a Unit' else x, y = coerce(other) y + x end end
[ "def", "+", "(", "other", ")", "case", "other", "when", "Unit", "if", "zero?", "other", ".", "dup", "elsif", "self", "=~", "other", "raise", "ArgumentError", ",", "'Cannot add two temperatures'", "if", "[", "self", ",", "other", "]", ".", "all?", "(", ":temperature?", ")", "if", "[", "self", ",", "other", "]", ".", "any?", "(", ":temperature?", ")", "if", "temperature?", "RubyUnits", "::", "Unit", ".", "new", "(", "scalar", ":", "(", "scalar", "+", "other", ".", "convert_to", "(", "temperature_scale", ")", ".", "scalar", ")", ",", "numerator", ":", "@numerator", ",", "denominator", ":", "@denominator", ",", "signature", ":", "@signature", ")", "else", "RubyUnits", "::", "Unit", ".", "new", "(", "scalar", ":", "(", "other", ".", "scalar", "+", "convert_to", "(", "other", ".", "temperature_scale", ")", ".", "scalar", ")", ",", "numerator", ":", "other", ".", "numerator", ",", "denominator", ":", "other", ".", "denominator", ",", "signature", ":", "other", ".", "signature", ")", "end", "else", "RubyUnits", "::", "Unit", ".", "new", "(", "scalar", ":", "(", "base_scalar", "+", "other", ".", "base_scalar", ")", ",", "numerator", ":", "base", ".", "numerator", ",", "denominator", ":", "base", ".", "denominator", ",", "signature", ":", "@signature", ")", ".", "convert_to", "(", "self", ")", "end", "else", "raise", "ArgumentError", ",", "\"Incompatible Units ('#{self}' not compatible with '#{other}')\"", "end", "when", "Date", ",", "Time", "raise", "ArgumentError", ",", "'Date and Time objects represent fixed points in time and cannot be added to a Unit'", "else", "x", ",", "y", "=", "coerce", "(", "other", ")", "y", "+", "x", "end", "end" ]
Add two units together. Result is same units as receiver and scalar and base_scalar are updated appropriately throws an exception if the units are not compatible. It is possible to add Time objects to units of time @param [Object] other @return [Unit] @raise [ArgumentError] when two temperatures are added @raise [ArgumentError] when units are not compatible @raise [ArgumentError] when adding a fixed time or date to a time span
[ "Add", "two", "units", "together", ".", "Result", "is", "same", "units", "as", "receiver", "and", "scalar", "and", "base_scalar", "are", "updated", "appropriately", "throws", "an", "exception", "if", "the", "units", "are", "not", "compatible", ".", "It", "is", "possible", "to", "add", "Time", "objects", "to", "units", "of", "time" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L835-L860
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.*
def *(other) case other when Unit raise ArgumentError, 'Cannot multiply by temperatures' if [other, self].any?(&:temperature?) opts = RubyUnits::Unit.eliminate_terms(@scalar * other.scalar, @numerator + other.numerator, @denominator + other.denominator) opts[:signature] = @signature + other.signature RubyUnits::Unit.new(opts) when Numeric RubyUnits::Unit.new(scalar: @scalar * other, numerator: @numerator, denominator: @denominator, signature: @signature) else x, y = coerce(other) x * y end end
ruby
def *(other) case other when Unit raise ArgumentError, 'Cannot multiply by temperatures' if [other, self].any?(&:temperature?) opts = RubyUnits::Unit.eliminate_terms(@scalar * other.scalar, @numerator + other.numerator, @denominator + other.denominator) opts[:signature] = @signature + other.signature RubyUnits::Unit.new(opts) when Numeric RubyUnits::Unit.new(scalar: @scalar * other, numerator: @numerator, denominator: @denominator, signature: @signature) else x, y = coerce(other) x * y end end
[ "def", "*", "(", "other", ")", "case", "other", "when", "Unit", "raise", "ArgumentError", ",", "'Cannot multiply by temperatures'", "if", "[", "other", ",", "self", "]", ".", "any?", "(", ":temperature?", ")", "opts", "=", "RubyUnits", "::", "Unit", ".", "eliminate_terms", "(", "@scalar", "*", "other", ".", "scalar", ",", "@numerator", "+", "other", ".", "numerator", ",", "@denominator", "+", "other", ".", "denominator", ")", "opts", "[", ":signature", "]", "=", "@signature", "+", "other", ".", "signature", "RubyUnits", "::", "Unit", ".", "new", "(", "opts", ")", "when", "Numeric", "RubyUnits", "::", "Unit", ".", "new", "(", "scalar", ":", "@scalar", "*", "other", ",", "numerator", ":", "@numerator", ",", "denominator", ":", "@denominator", ",", "signature", ":", "@signature", ")", "else", "x", ",", "y", "=", "coerce", "(", "other", ")", "x", "*", "y", "end", "end" ]
Multiply two units. @param [Numeric] other @return [Unit] @raise [ArgumentError] when attempting to multiply two temperatures
[ "Multiply", "two", "units", "." ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L902-L915
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit./
def /(other) case other when Unit raise ZeroDivisionError if other.zero? raise ArgumentError, 'Cannot divide with temperatures' if [other, self].any?(&:temperature?) sc = Rational(@scalar, other.scalar) sc = sc.numerator if sc.denominator == 1 opts = RubyUnits::Unit.eliminate_terms(sc, @numerator + other.denominator, @denominator + other.numerator) opts[:signature] = @signature - other.signature RubyUnits::Unit.new(opts) when Numeric raise ZeroDivisionError if other.zero? sc = Rational(@scalar, other) sc = sc.numerator if sc.denominator == 1 RubyUnits::Unit.new(scalar: sc, numerator: @numerator, denominator: @denominator, signature: @signature) else x, y = coerce(other) y / x end end
ruby
def /(other) case other when Unit raise ZeroDivisionError if other.zero? raise ArgumentError, 'Cannot divide with temperatures' if [other, self].any?(&:temperature?) sc = Rational(@scalar, other.scalar) sc = sc.numerator if sc.denominator == 1 opts = RubyUnits::Unit.eliminate_terms(sc, @numerator + other.denominator, @denominator + other.numerator) opts[:signature] = @signature - other.signature RubyUnits::Unit.new(opts) when Numeric raise ZeroDivisionError if other.zero? sc = Rational(@scalar, other) sc = sc.numerator if sc.denominator == 1 RubyUnits::Unit.new(scalar: sc, numerator: @numerator, denominator: @denominator, signature: @signature) else x, y = coerce(other) y / x end end
[ "def", "/", "(", "other", ")", "case", "other", "when", "Unit", "raise", "ZeroDivisionError", "if", "other", ".", "zero?", "raise", "ArgumentError", ",", "'Cannot divide with temperatures'", "if", "[", "other", ",", "self", "]", ".", "any?", "(", ":temperature?", ")", "sc", "=", "Rational", "(", "@scalar", ",", "other", ".", "scalar", ")", "sc", "=", "sc", ".", "numerator", "if", "sc", ".", "denominator", "==", "1", "opts", "=", "RubyUnits", "::", "Unit", ".", "eliminate_terms", "(", "sc", ",", "@numerator", "+", "other", ".", "denominator", ",", "@denominator", "+", "other", ".", "numerator", ")", "opts", "[", ":signature", "]", "=", "@signature", "-", "other", ".", "signature", "RubyUnits", "::", "Unit", ".", "new", "(", "opts", ")", "when", "Numeric", "raise", "ZeroDivisionError", "if", "other", ".", "zero?", "sc", "=", "Rational", "(", "@scalar", ",", "other", ")", "sc", "=", "sc", ".", "numerator", "if", "sc", ".", "denominator", "==", "1", "RubyUnits", "::", "Unit", ".", "new", "(", "scalar", ":", "sc", ",", "numerator", ":", "@numerator", ",", "denominator", ":", "@denominator", ",", "signature", ":", "@signature", ")", "else", "x", ",", "y", "=", "coerce", "(", "other", ")", "y", "/", "x", "end", "end" ]
Divide two units. Throws an exception if divisor is 0 @param [Numeric] other @return [Unit] @raise [ZeroDivisionError] if divisor is zero @raise [ArgumentError] if attempting to divide a temperature by another temperature
[ "Divide", "two", "units", ".", "Throws", "an", "exception", "if", "divisor", "is", "0" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L923-L942
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.divmod
def divmod(other) raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" unless self =~ other return scalar.divmod(other.scalar) if units == other.units to_base.scalar.divmod(other.to_base.scalar) end
ruby
def divmod(other) raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" unless self =~ other return scalar.divmod(other.scalar) if units == other.units to_base.scalar.divmod(other.to_base.scalar) end
[ "def", "divmod", "(", "other", ")", "raise", "ArgumentError", ",", "\"Incompatible Units ('#{self}' not compatible with '#{other}')\"", "unless", "self", "=~", "other", "return", "scalar", ".", "divmod", "(", "other", ".", "scalar", ")", "if", "units", "==", "other", ".", "units", "to_base", ".", "scalar", ".", "divmod", "(", "other", ".", "to_base", ".", "scalar", ")", "end" ]
divide two units and return quotient and remainder when both units are in the same units we just use divmod on the raw scalars otherwise we use the scalar of the base unit which will be a float @param [Object] other @return [Array]
[ "divide", "two", "units", "and", "return", "quotient", "and", "remainder", "when", "both", "units", "are", "in", "the", "same", "units", "we", "just", "use", "divmod", "on", "the", "raw", "scalars", "otherwise", "we", "use", "the", "scalar", "of", "the", "base", "unit", "which", "will", "be", "a", "float" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L949-L953
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.**
def **(other) raise ArgumentError, 'Cannot raise a temperature to a power' if temperature? if other.is_a?(Numeric) return inverse if other == -1 return self if other == 1 return 1 if other.zero? end case other when Rational return power(other.numerator).root(other.denominator) when Integer return power(other) when Float return self**other.to_i if other == other.to_i valid = (1..9).map { |n| Rational(1, n) } raise ArgumentError, 'Not a n-th root (1..9), use 1/n' unless valid.include? other.abs return root(Rational(1, other).to_int) when Complex raise ArgumentError, 'exponentiation of complex numbers is not supported.' else raise ArgumentError, 'Invalid Exponent' end end
ruby
def **(other) raise ArgumentError, 'Cannot raise a temperature to a power' if temperature? if other.is_a?(Numeric) return inverse if other == -1 return self if other == 1 return 1 if other.zero? end case other when Rational return power(other.numerator).root(other.denominator) when Integer return power(other) when Float return self**other.to_i if other == other.to_i valid = (1..9).map { |n| Rational(1, n) } raise ArgumentError, 'Not a n-th root (1..9), use 1/n' unless valid.include? other.abs return root(Rational(1, other).to_int) when Complex raise ArgumentError, 'exponentiation of complex numbers is not supported.' else raise ArgumentError, 'Invalid Exponent' end end
[ "def", "**", "(", "other", ")", "raise", "ArgumentError", ",", "'Cannot raise a temperature to a power'", "if", "temperature?", "if", "other", ".", "is_a?", "(", "Numeric", ")", "return", "inverse", "if", "other", "==", "-", "1", "return", "self", "if", "other", "==", "1", "return", "1", "if", "other", ".", "zero?", "end", "case", "other", "when", "Rational", "return", "power", "(", "other", ".", "numerator", ")", ".", "root", "(", "other", ".", "denominator", ")", "when", "Integer", "return", "power", "(", "other", ")", "when", "Float", "return", "self", "**", "other", ".", "to_i", "if", "other", "==", "other", ".", "to_i", "valid", "=", "(", "1", "..", "9", ")", ".", "map", "{", "|", "n", "|", "Rational", "(", "1", ",", "n", ")", "}", "raise", "ArgumentError", ",", "'Not a n-th root (1..9), use 1/n'", "unless", "valid", ".", "include?", "other", ".", "abs", "return", "root", "(", "Rational", "(", "1", ",", "other", ")", ".", "to_int", ")", "when", "Complex", "raise", "ArgumentError", ",", "'exponentiation of complex numbers is not supported.'", "else", "raise", "ArgumentError", ",", "'Invalid Exponent'", "end", "end" ]
Exponentiate. Only takes integer powers. Note that anything raised to the power of 0 results in a Unit object with a scalar of 1, and no units. Throws an exception if exponent is not an integer. Ideally this routine should accept a float for the exponent It should then convert the float to a rational and raise the unit by the numerator and root it by the denominator but, sadly, floats can't be converted to rationals. For now, if a rational is passed in, it will be used, otherwise we are stuck with integers and certain floats < 1 @param [Numeric] other @return [Unit] @raise [ArgumentError] when raising a temperature to a power @raise [ArgumentError] when n not in the set integers from (1..9) @raise [ArgumentError] when attempting to raise to a complex number @raise [ArgumentError] when an invalid exponent is passed
[ "Exponentiate", ".", "Only", "takes", "integer", "powers", ".", "Note", "that", "anything", "raised", "to", "the", "power", "of", "0", "results", "in", "a", "Unit", "object", "with", "a", "scalar", "of", "1", "and", "no", "units", ".", "Throws", "an", "exception", "if", "exponent", "is", "not", "an", "integer", ".", "Ideally", "this", "routine", "should", "accept", "a", "float", "for", "the", "exponent", "It", "should", "then", "convert", "the", "float", "to", "a", "rational", "and", "raise", "the", "unit", "by", "the", "numerator", "and", "root", "it", "by", "the", "denominator", "but", "sadly", "floats", "can", "t", "be", "converted", "to", "rationals", "." ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L976-L998
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.power
def power(n) raise ArgumentError, 'Cannot raise a temperature to a power' if temperature? raise ArgumentError, 'Exponent must an Integer' unless n.is_a?(Integer) return inverse if n == -1 return 1 if n.zero? return self if n == 1 return (1..(n - 1).to_i).inject(self) { |acc, _elem| acc * self } if n >= 0 (1..-(n - 1).to_i).inject(self) { |acc, _elem| acc / self } end
ruby
def power(n) raise ArgumentError, 'Cannot raise a temperature to a power' if temperature? raise ArgumentError, 'Exponent must an Integer' unless n.is_a?(Integer) return inverse if n == -1 return 1 if n.zero? return self if n == 1 return (1..(n - 1).to_i).inject(self) { |acc, _elem| acc * self } if n >= 0 (1..-(n - 1).to_i).inject(self) { |acc, _elem| acc / self } end
[ "def", "power", "(", "n", ")", "raise", "ArgumentError", ",", "'Cannot raise a temperature to a power'", "if", "temperature?", "raise", "ArgumentError", ",", "'Exponent must an Integer'", "unless", "n", ".", "is_a?", "(", "Integer", ")", "return", "inverse", "if", "n", "==", "-", "1", "return", "1", "if", "n", ".", "zero?", "return", "self", "if", "n", "==", "1", "return", "(", "1", "..", "(", "n", "-", "1", ")", ".", "to_i", ")", ".", "inject", "(", "self", ")", "{", "|", "acc", ",", "_elem", "|", "acc", "*", "self", "}", "if", "n", ">=", "0", "(", "1", "..", "-", "(", "n", "-", "1", ")", ".", "to_i", ")", ".", "inject", "(", "self", ")", "{", "|", "acc", ",", "_elem", "|", "acc", "/", "self", "}", "end" ]
returns the unit raised to the n-th power @param [Integer] n @return [Unit] @raise [ArgumentError] when attempting to raise a temperature to a power @raise [ArgumentError] when n is not an integer
[ "returns", "the", "unit", "raised", "to", "the", "n", "-", "th", "power" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L1005-L1013
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.units
def units(with_prefix: true) return '' if @numerator == UNITY_ARRAY && @denominator == UNITY_ARRAY output_numerator = ['1'] output_denominator = [] num = @numerator.clone.compact den = @denominator.clone.compact unless num == UNITY_ARRAY definitions = num.map { |element| RubyUnits::Unit.definition(element) } definitions.reject!(&:prefix?) unless with_prefix # there is a bug in jruby 9.1.6.0's implementation of chunk_while # see https://github.com/jruby/jruby/issues/4410 # TODO: fix this after jruby fixes their bug. definitions = if definitions.respond_to?(:chunk_while) && RUBY_ENGINE != 'jruby' definitions.chunk_while { |defn, _| defn.prefix? }.to_a else # chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby result = [] enumerator = definitions.to_enum loop do first = enumerator.next result << (first.prefix? ? [first, enumerator.next] : [first]) end result end output_numerator = definitions.map { |element| element.map(&:display_name).join } end unless den == UNITY_ARRAY definitions = den.map { |element| RubyUnits::Unit.definition(element) } definitions.reject!(&:prefix?) unless with_prefix # there is a bug in jruby 9.1.6.0's implementation of chunk_while # see https://github.com/jruby/jruby/issues/4410 # TODO: fix this after jruby fixes their bug. definitions = if definitions.respond_to?(:chunk_while) && RUBY_ENGINE != 'jruby' definitions.chunk_while { |defn, _| defn.prefix? }.to_a else # chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby result = [] enumerator = definitions.to_enum loop do first = enumerator.next result << (first.prefix? ? [first, enumerator.next] : [first]) end result end output_denominator = definitions.map { |element| element.map(&:display_name).join } end on = output_numerator .uniq .map { |x| [x, output_numerator.count(x)] } .map { |element, power| (element.to_s.strip + (power > 1 ? "^#{power}" : '')) } od = output_denominator .uniq .map { |x| [x, output_denominator.count(x)] } .map { |element, power| (element.to_s.strip + (power > 1 ? "^#{power}" : '')) } "#{on.join('*')}#{od.empty? ? '' : '/' + od.join('*')}".strip end
ruby
def units(with_prefix: true) return '' if @numerator == UNITY_ARRAY && @denominator == UNITY_ARRAY output_numerator = ['1'] output_denominator = [] num = @numerator.clone.compact den = @denominator.clone.compact unless num == UNITY_ARRAY definitions = num.map { |element| RubyUnits::Unit.definition(element) } definitions.reject!(&:prefix?) unless with_prefix # there is a bug in jruby 9.1.6.0's implementation of chunk_while # see https://github.com/jruby/jruby/issues/4410 # TODO: fix this after jruby fixes their bug. definitions = if definitions.respond_to?(:chunk_while) && RUBY_ENGINE != 'jruby' definitions.chunk_while { |defn, _| defn.prefix? }.to_a else # chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby result = [] enumerator = definitions.to_enum loop do first = enumerator.next result << (first.prefix? ? [first, enumerator.next] : [first]) end result end output_numerator = definitions.map { |element| element.map(&:display_name).join } end unless den == UNITY_ARRAY definitions = den.map { |element| RubyUnits::Unit.definition(element) } definitions.reject!(&:prefix?) unless with_prefix # there is a bug in jruby 9.1.6.0's implementation of chunk_while # see https://github.com/jruby/jruby/issues/4410 # TODO: fix this after jruby fixes their bug. definitions = if definitions.respond_to?(:chunk_while) && RUBY_ENGINE != 'jruby' definitions.chunk_while { |defn, _| defn.prefix? }.to_a else # chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby result = [] enumerator = definitions.to_enum loop do first = enumerator.next result << (first.prefix? ? [first, enumerator.next] : [first]) end result end output_denominator = definitions.map { |element| element.map(&:display_name).join } end on = output_numerator .uniq .map { |x| [x, output_numerator.count(x)] } .map { |element, power| (element.to_s.strip + (power > 1 ? "^#{power}" : '')) } od = output_denominator .uniq .map { |x| [x, output_denominator.count(x)] } .map { |element, power| (element.to_s.strip + (power > 1 ? "^#{power}" : '')) } "#{on.join('*')}#{od.empty? ? '' : '/' + od.join('*')}".strip end
[ "def", "units", "(", "with_prefix", ":", "true", ")", "return", "''", "if", "@numerator", "==", "UNITY_ARRAY", "&&", "@denominator", "==", "UNITY_ARRAY", "output_numerator", "=", "[", "'1'", "]", "output_denominator", "=", "[", "]", "num", "=", "@numerator", ".", "clone", ".", "compact", "den", "=", "@denominator", ".", "clone", ".", "compact", "unless", "num", "==", "UNITY_ARRAY", "definitions", "=", "num", ".", "map", "{", "|", "element", "|", "RubyUnits", "::", "Unit", ".", "definition", "(", "element", ")", "}", "definitions", ".", "reject!", "(", ":prefix?", ")", "unless", "with_prefix", "# there is a bug in jruby 9.1.6.0's implementation of chunk_while", "# see https://github.com/jruby/jruby/issues/4410", "# TODO: fix this after jruby fixes their bug.", "definitions", "=", "if", "definitions", ".", "respond_to?", "(", ":chunk_while", ")", "&&", "RUBY_ENGINE", "!=", "'jruby'", "definitions", ".", "chunk_while", "{", "|", "defn", ",", "_", "|", "defn", ".", "prefix?", "}", ".", "to_a", "else", "# chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby", "result", "=", "[", "]", "enumerator", "=", "definitions", ".", "to_enum", "loop", "do", "first", "=", "enumerator", ".", "next", "result", "<<", "(", "first", ".", "prefix?", "?", "[", "first", ",", "enumerator", ".", "next", "]", ":", "[", "first", "]", ")", "end", "result", "end", "output_numerator", "=", "definitions", ".", "map", "{", "|", "element", "|", "element", ".", "map", "(", ":display_name", ")", ".", "join", "}", "end", "unless", "den", "==", "UNITY_ARRAY", "definitions", "=", "den", ".", "map", "{", "|", "element", "|", "RubyUnits", "::", "Unit", ".", "definition", "(", "element", ")", "}", "definitions", ".", "reject!", "(", ":prefix?", ")", "unless", "with_prefix", "# there is a bug in jruby 9.1.6.0's implementation of chunk_while", "# see https://github.com/jruby/jruby/issues/4410", "# TODO: fix this after jruby fixes their bug.", "definitions", "=", "if", "definitions", ".", "respond_to?", "(", ":chunk_while", ")", "&&", "RUBY_ENGINE", "!=", "'jruby'", "definitions", ".", "chunk_while", "{", "|", "defn", ",", "_", "|", "defn", ".", "prefix?", "}", ".", "to_a", "else", "# chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby", "result", "=", "[", "]", "enumerator", "=", "definitions", ".", "to_enum", "loop", "do", "first", "=", "enumerator", ".", "next", "result", "<<", "(", "first", ".", "prefix?", "?", "[", "first", ",", "enumerator", ".", "next", "]", ":", "[", "first", "]", ")", "end", "result", "end", "output_denominator", "=", "definitions", ".", "map", "{", "|", "element", "|", "element", ".", "map", "(", ":display_name", ")", ".", "join", "}", "end", "on", "=", "output_numerator", ".", "uniq", ".", "map", "{", "|", "x", "|", "[", "x", ",", "output_numerator", ".", "count", "(", "x", ")", "]", "}", ".", "map", "{", "|", "element", ",", "power", "|", "(", "element", ".", "to_s", ".", "strip", "+", "(", "power", ">", "1", "?", "\"^#{power}\"", ":", "''", ")", ")", "}", "od", "=", "output_denominator", ".", "uniq", ".", "map", "{", "|", "x", "|", "[", "x", ",", "output_denominator", ".", "count", "(", "x", ")", "]", "}", ".", "map", "{", "|", "element", ",", "power", "|", "(", "element", ".", "to_s", ".", "strip", "+", "(", "power", ">", "1", "?", "\"^#{power}\"", ":", "''", ")", ")", "}", "\"#{on.join('*')}#{od.empty? ? '' : '/' + od.join('*')}\"", ".", "strip", "end" ]
returns the 'unit' part of the Unit object without the scalar @return [String]
[ "returns", "the", "unit", "part", "of", "the", "Unit", "object", "without", "the", "scalar" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L1174-L1230
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.coerce
def coerce(other) return [other.to_unit, self] if other.respond_to? :to_unit case other when Unit [other, self] else [RubyUnits::Unit.new(other), self] end end
ruby
def coerce(other) return [other.to_unit, self] if other.respond_to? :to_unit case other when Unit [other, self] else [RubyUnits::Unit.new(other), self] end end
[ "def", "coerce", "(", "other", ")", "return", "[", "other", ".", "to_unit", ",", "self", "]", "if", "other", ".", "respond_to?", ":to_unit", "case", "other", "when", "Unit", "[", "other", ",", "self", "]", "else", "[", "RubyUnits", "::", "Unit", ".", "new", "(", "other", ")", ",", "self", "]", "end", "end" ]
automatically coerce objects to units when possible if an object defines a 'to_unit' method, it will be coerced using that method @param [Object, #to_unit] @return [Array]
[ "automatically", "coerce", "objects", "to", "units", "when", "possible", "if", "an", "object", "defines", "a", "to_unit", "method", "it", "will", "be", "coerced", "using", "that", "method" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L1393-L1401
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.best_prefix
def best_prefix return to_base if scalar.zero? best_prefix = if kind == :information @@prefix_values.key(2**((Math.log(base_scalar, 2) / 10.0).floor * 10)) else @@prefix_values.key(10**((Math.log10(base_scalar) / 3.0).floor * 3)) end to(RubyUnits::Unit.new(@@prefix_map.key(best_prefix) + units(with_prefix: false))) end
ruby
def best_prefix return to_base if scalar.zero? best_prefix = if kind == :information @@prefix_values.key(2**((Math.log(base_scalar, 2) / 10.0).floor * 10)) else @@prefix_values.key(10**((Math.log10(base_scalar) / 3.0).floor * 3)) end to(RubyUnits::Unit.new(@@prefix_map.key(best_prefix) + units(with_prefix: false))) end
[ "def", "best_prefix", "return", "to_base", "if", "scalar", ".", "zero?", "best_prefix", "=", "if", "kind", "==", ":information", "@@prefix_values", ".", "key", "(", "2", "**", "(", "(", "Math", ".", "log", "(", "base_scalar", ",", "2", ")", "/", "10.0", ")", ".", "floor", "*", "10", ")", ")", "else", "@@prefix_values", ".", "key", "(", "10", "**", "(", "(", "Math", ".", "log10", "(", "base_scalar", ")", "/", "3.0", ")", ".", "floor", "*", "3", ")", ")", "end", "to", "(", "RubyUnits", "::", "Unit", ".", "new", "(", "@@prefix_map", ".", "key", "(", "best_prefix", ")", "+", "units", "(", "with_prefix", ":", "false", ")", ")", ")", "end" ]
returns a new unit that has been scaled to be more in line with typical usage.
[ "returns", "a", "new", "unit", "that", "has", "been", "scaled", "to", "be", "more", "in", "line", "with", "typical", "usage", "." ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L1404-L1412
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.unit_signature_vector
def unit_signature_vector return to_base.unit_signature_vector unless base? vector = Array.new(SIGNATURE_VECTOR.size, 0) # it's possible to have a kind that misses the array... kinds like :counting # are more like prefixes, so don't use them to calculate the vector @numerator.map { |element| RubyUnits::Unit.definition(element) }.each do |definition| index = SIGNATURE_VECTOR.index(definition.kind) vector[index] += 1 if index end @denominator.map { |element| RubyUnits::Unit.definition(element) }.each do |definition| index = SIGNATURE_VECTOR.index(definition.kind) vector[index] -= 1 if index end raise ArgumentError, 'Power out of range (-20 < net power of a unit < 20)' if vector.any? { |x| x.abs >= 20 } vector end
ruby
def unit_signature_vector return to_base.unit_signature_vector unless base? vector = Array.new(SIGNATURE_VECTOR.size, 0) # it's possible to have a kind that misses the array... kinds like :counting # are more like prefixes, so don't use them to calculate the vector @numerator.map { |element| RubyUnits::Unit.definition(element) }.each do |definition| index = SIGNATURE_VECTOR.index(definition.kind) vector[index] += 1 if index end @denominator.map { |element| RubyUnits::Unit.definition(element) }.each do |definition| index = SIGNATURE_VECTOR.index(definition.kind) vector[index] -= 1 if index end raise ArgumentError, 'Power out of range (-20 < net power of a unit < 20)' if vector.any? { |x| x.abs >= 20 } vector end
[ "def", "unit_signature_vector", "return", "to_base", ".", "unit_signature_vector", "unless", "base?", "vector", "=", "Array", ".", "new", "(", "SIGNATURE_VECTOR", ".", "size", ",", "0", ")", "# it's possible to have a kind that misses the array... kinds like :counting", "# are more like prefixes, so don't use them to calculate the vector", "@numerator", ".", "map", "{", "|", "element", "|", "RubyUnits", "::", "Unit", ".", "definition", "(", "element", ")", "}", ".", "each", "do", "|", "definition", "|", "index", "=", "SIGNATURE_VECTOR", ".", "index", "(", "definition", ".", "kind", ")", "vector", "[", "index", "]", "+=", "1", "if", "index", "end", "@denominator", ".", "map", "{", "|", "element", "|", "RubyUnits", "::", "Unit", ".", "definition", "(", "element", ")", "}", ".", "each", "do", "|", "definition", "|", "index", "=", "SIGNATURE_VECTOR", ".", "index", "(", "definition", ".", "kind", ")", "vector", "[", "index", "]", "-=", "1", "if", "index", "end", "raise", "ArgumentError", ",", "'Power out of range (-20 < net power of a unit < 20)'", "if", "vector", ".", "any?", "{", "|", "x", "|", "x", ".", "abs", ">=", "20", "}", "vector", "end" ]
calculates the unit signature vector used by unit_signature @return [Array] @raise [ArgumentError] when exponent associated with a unit is > 20 or < -20
[ "calculates", "the", "unit", "signature", "vector", "used", "by", "unit_signature" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L1446-L1461
train
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.unit_signature
def unit_signature return @signature unless @signature.nil? vector = unit_signature_vector vector.each_with_index { |item, index| vector[index] = item * 20**index } @signature = vector.inject(0) { |acc, elem| acc + elem } @signature end
ruby
def unit_signature return @signature unless @signature.nil? vector = unit_signature_vector vector.each_with_index { |item, index| vector[index] = item * 20**index } @signature = vector.inject(0) { |acc, elem| acc + elem } @signature end
[ "def", "unit_signature", "return", "@signature", "unless", "@signature", ".", "nil?", "vector", "=", "unit_signature_vector", "vector", ".", "each_with_index", "{", "|", "item", ",", "index", "|", "vector", "[", "index", "]", "=", "item", "*", "20", "**", "index", "}", "@signature", "=", "vector", ".", "inject", "(", "0", ")", "{", "|", "acc", ",", "elem", "|", "acc", "+", "elem", "}", "@signature", "end" ]
calculates the unit signature id for use in comparing compatible units and simplification the signature is based on a simple classification of units and is based on the following publication Novak, G.S., Jr. "Conversion of units of measurement", IEEE Transactions on Software Engineering, 21(8), Aug 1995, pp.651-661 @see http://doi.ieeecomputersociety.org/10.1109/32.403789 @return [Array]
[ "calculates", "the", "unit", "signature", "id", "for", "use", "in", "comparing", "compatible", "units", "and", "simplification", "the", "signature", "is", "based", "on", "a", "simple", "classification", "of", "units", "and", "is", "based", "on", "the", "following", "publication" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L1479-L1485
train
jonhue/acts_as_favoritor
lib/acts_as_favoritor/favoritor_lib.rb
ActsAsFavoritor.FavoritorLib.parent_class_name
def parent_class_name(obj) unless DEFAULT_PARENTS.include? obj.class.superclass return obj.class.base_class.name end obj.class.name end
ruby
def parent_class_name(obj) unless DEFAULT_PARENTS.include? obj.class.superclass return obj.class.base_class.name end obj.class.name end
[ "def", "parent_class_name", "(", "obj", ")", "unless", "DEFAULT_PARENTS", ".", "include?", "obj", ".", "class", ".", "superclass", "return", "obj", ".", "class", ".", "base_class", ".", "name", "end", "obj", ".", "class", ".", "name", "end" ]
Retrieves the parent class name if using STI.
[ "Retrieves", "the", "parent", "class", "name", "if", "using", "STI", "." ]
d85342b2d8d2b5bab328f980bb351a667faafb3a
https://github.com/jonhue/acts_as_favoritor/blob/d85342b2d8d2b5bab328f980bb351a667faafb3a/lib/acts_as_favoritor/favoritor_lib.rb#L10-L16
train
moneta-rb/moneta
lib/moneta/mixins.rb
Moneta.OptionSupport.with
def with(options = nil, &block) adapter = self if block builder = Builder.new(&block) builder.adapter(adapter) adapter = builder.build.last end options ? OptionMerger.new(adapter, options) : adapter end
ruby
def with(options = nil, &block) adapter = self if block builder = Builder.new(&block) builder.adapter(adapter) adapter = builder.build.last end options ? OptionMerger.new(adapter, options) : adapter end
[ "def", "with", "(", "options", "=", "nil", ",", "&", "block", ")", "adapter", "=", "self", "if", "block", "builder", "=", "Builder", ".", "new", "(", "block", ")", "builder", ".", "adapter", "(", "adapter", ")", "adapter", "=", "builder", ".", "build", ".", "last", "end", "options", "?", "OptionMerger", ".", "new", "(", "adapter", ",", "options", ")", ":", "adapter", "end" ]
Return Moneta store with default options or additional proxies @param [Hash] options Options to merge @return [Moneta store] @api public
[ "Return", "Moneta", "store", "with", "default", "options", "or", "additional", "proxies" ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/mixins.rb#L10-L18
train
moneta-rb/moneta
lib/moneta/mixins.rb
Moneta.Defaults.fetch
def fetch(key, default = nil, options = nil) if block_given? raise ArgumentError, 'Only one argument accepted if block is given' if options result = load(key, default || {}) result == nil ? yield(key) : result else result = load(key, options || {}) result == nil ? default : result end end
ruby
def fetch(key, default = nil, options = nil) if block_given? raise ArgumentError, 'Only one argument accepted if block is given' if options result = load(key, default || {}) result == nil ? yield(key) : result else result = load(key, options || {}) result == nil ? default : result end end
[ "def", "fetch", "(", "key", ",", "default", "=", "nil", ",", "options", "=", "nil", ")", "if", "block_given?", "raise", "ArgumentError", ",", "'Only one argument accepted if block is given'", "if", "options", "result", "=", "load", "(", "key", ",", "default", "||", "{", "}", ")", "result", "==", "nil", "?", "yield", "(", "key", ")", ":", "result", "else", "result", "=", "load", "(", "key", ",", "options", "||", "{", "}", ")", "result", "==", "nil", "?", "default", ":", "result", "end", "end" ]
Fetch a value with a key @overload fetch(key, options = {}, &block) retrieve a key. if the key is not available, execute the block and return its return value. @param [Object] key @param [Hash] options @option options [Integer] :expires Update expiration time (See {Expires}) @option options [Boolean] :raw Raw access without value transformation (See {Transformer}) @option options [String] :prefix Prefix key (See {Transformer}) @return [Object] value from store @overload fetch(key, default, options = {}) retrieve a key. if the key is not available, return the default value. @param [Object] key @param [Object] default Default value @param [Hash] options @option options [Integer] :expires Update expiration time (See {Expires}) @option options [Boolean] :raw Raw access without value transformation (See {Transformer}) @option options [String] :prefix Prefix key (See {Transformer}) @return [Object] value from store @api public
[ "Fetch", "a", "value", "with", "a", "key" ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/mixins.rb#L180-L189
train
moneta-rb/moneta
lib/moneta/mixins.rb
Moneta.Defaults.slice
def slice(*keys, **options) keys.zip(values_at(*keys, **options)).reject do |_, value| value == nil end end
ruby
def slice(*keys, **options) keys.zip(values_at(*keys, **options)).reject do |_, value| value == nil end end
[ "def", "slice", "(", "*", "keys", ",", "**", "options", ")", "keys", ".", "zip", "(", "values_at", "(", "keys", ",", "**", "options", ")", ")", ".", "reject", "do", "|", "_", ",", "value", "|", "value", "==", "nil", "end", "end" ]
Returns a collection of key-value pairs corresponding to those supplied keys which are present in the key-value store, and their associated values. Only those keys present in the store will have pairs in the return value. The return value can be any enumerable object that yields pairs, so it could be a hash, but needn't be. @note The keys in the return value may be the same objects that were supplied (i.e. {Object#equal?}), or may simply be equal (i.e. {Object#==}). @note Some adapters may implement this method atomically. The default implmentation uses {#values_at}. @param (see #values_at) @option options (see #values_at) @return [<(Object, Object)>] A collection of key-value pairs @api public
[ "Returns", "a", "collection", "of", "key", "-", "value", "pairs", "corresponding", "to", "those", "supplied", "keys", "which", "are", "present", "in", "the", "key", "-", "value", "store", "and", "their", "associated", "values", ".", "Only", "those", "keys", "present", "in", "the", "store", "will", "have", "pairs", "in", "the", "return", "value", ".", "The", "return", "value", "can", "be", "any", "enumerable", "object", "that", "yields", "pairs", "so", "it", "could", "be", "a", "hash", "but", "needn", "t", "be", "." ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/mixins.rb#L311-L315
train
moneta-rb/moneta
lib/moneta/mixins.rb
Moneta.ExpiresSupport.expires_at
def expires_at(options, default = @default_expires) value = expires_value(options, default) Numeric === value ? Time.now + value : value end
ruby
def expires_at(options, default = @default_expires) value = expires_value(options, default) Numeric === value ? Time.now + value : value end
[ "def", "expires_at", "(", "options", ",", "default", "=", "@default_expires", ")", "value", "=", "expires_value", "(", "options", ",", "default", ")", "Numeric", "===", "value", "?", "Time", ".", "now", "+", "value", ":", "value", "end" ]
Calculates the time when something will expire. This method considers false and 0 as "no-expire" and every positive number as a time to live in seconds. @param [Hash] options Options hash @option options [0,false,nil,Numeric] :expires expires value given by user @param [0,false,nil,Numeric] default default expiration time @return [false] if it should not expire @return [Time] the time when something should expire @return [nil] if it is not known
[ "Calculates", "the", "time", "when", "something", "will", "expire", "." ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/mixins.rb#L583-L586
train
moneta-rb/moneta
lib/moneta/mixins.rb
Moneta.ExpiresSupport.expires_value
def expires_value(options, default = @default_expires) case value = options[:expires] when 0, false false when nil default ? default.to_r : nil when Numeric value = value.to_r raise ArgumentError, ":expires must be a positive value, got #{value}" if value < 0 value else raise ArgumentError, ":expires must be Numeric or false, got #{value.inspect}" end end
ruby
def expires_value(options, default = @default_expires) case value = options[:expires] when 0, false false when nil default ? default.to_r : nil when Numeric value = value.to_r raise ArgumentError, ":expires must be a positive value, got #{value}" if value < 0 value else raise ArgumentError, ":expires must be Numeric or false, got #{value.inspect}" end end
[ "def", "expires_value", "(", "options", ",", "default", "=", "@default_expires", ")", "case", "value", "=", "options", "[", ":expires", "]", "when", "0", ",", "false", "false", "when", "nil", "default", "?", "default", ".", "to_r", ":", "nil", "when", "Numeric", "value", "=", "value", ".", "to_r", "raise", "ArgumentError", ",", "\":expires must be a positive value, got #{value}\"", "if", "value", "<", "0", "value", "else", "raise", "ArgumentError", ",", "\":expires must be Numeric or false, got #{value.inspect}\"", "end", "end" ]
Calculates the number of seconds something should last. This method considers false and 0 as "no-expire" and every positive number as a time to live in seconds. @param [Hash] options Options hash @option options [0,false,nil,Numeric] :expires expires value given by user @param [0,false,nil,Numeric] default default expiration time @return [false] if it should not expire @return [Numeric] seconds until expiration @return [nil] if it is not known
[ "Calculates", "the", "number", "of", "seconds", "something", "should", "last", "." ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/mixins.rb#L600-L613
train
moneta-rb/moneta
lib/moneta/builder.rb
Moneta.Builder.use
def use(proxy, options = {}, &block) proxy = Moneta.const_get(proxy) if Symbol === proxy raise ArgumentError, 'You must give a Class or a Symbol' unless Class === proxy @proxies.unshift [proxy, options, block] nil end
ruby
def use(proxy, options = {}, &block) proxy = Moneta.const_get(proxy) if Symbol === proxy raise ArgumentError, 'You must give a Class or a Symbol' unless Class === proxy @proxies.unshift [proxy, options, block] nil end
[ "def", "use", "(", "proxy", ",", "options", "=", "{", "}", ",", "&", "block", ")", "proxy", "=", "Moneta", ".", "const_get", "(", "proxy", ")", "if", "Symbol", "===", "proxy", "raise", "ArgumentError", ",", "'You must give a Class or a Symbol'", "unless", "Class", "===", "proxy", "@proxies", ".", "unshift", "[", "proxy", ",", "options", ",", "block", "]", "nil", "end" ]
Add proxy to stack @param [Symbol/Class] proxy Name of proxy class or proxy class @param [Hash] options Options hash @api public
[ "Add", "proxy", "to", "stack" ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/builder.rb#L36-L41
train
moneta-rb/moneta
lib/moneta/builder.rb
Moneta.Builder.adapter
def adapter(adapter, options = {}, &block) case adapter when Symbol use(Adapters.const_get(adapter), options, &block) when Class use(adapter, options, &block) else raise ArgumentError, 'Adapter must be a Moneta store' unless adapter.respond_to?(:load) && adapter.respond_to?(:store) raise ArgumentError, 'No options allowed' unless options.empty? @proxies.unshift adapter nil end end
ruby
def adapter(adapter, options = {}, &block) case adapter when Symbol use(Adapters.const_get(adapter), options, &block) when Class use(adapter, options, &block) else raise ArgumentError, 'Adapter must be a Moneta store' unless adapter.respond_to?(:load) && adapter.respond_to?(:store) raise ArgumentError, 'No options allowed' unless options.empty? @proxies.unshift adapter nil end end
[ "def", "adapter", "(", "adapter", ",", "options", "=", "{", "}", ",", "&", "block", ")", "case", "adapter", "when", "Symbol", "use", "(", "Adapters", ".", "const_get", "(", "adapter", ")", ",", "options", ",", "block", ")", "when", "Class", "use", "(", "adapter", ",", "options", ",", "block", ")", "else", "raise", "ArgumentError", ",", "'Adapter must be a Moneta store'", "unless", "adapter", ".", "respond_to?", "(", ":load", ")", "&&", "adapter", ".", "respond_to?", "(", ":store", ")", "raise", "ArgumentError", ",", "'No options allowed'", "unless", "options", ".", "empty?", "@proxies", ".", "unshift", "adapter", "nil", "end", "end" ]
Add adapter to stack @param [Symbol/Class/Moneta store] adapter Name of adapter class, adapter class or Moneta store @param [Hash] options Options hash @api public
[ "Add", "adapter", "to", "stack" ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/builder.rb#L48-L60
train
moneta-rb/moneta
lib/moneta/server.rb
Moneta.Server.run
def run raise 'Already running' if @running @stop = false @running = true begin until @stop mainloop end ensure File.unlink(@socket) if @socket @ios.each{ |io| io.close rescue nil } end end
ruby
def run raise 'Already running' if @running @stop = false @running = true begin until @stop mainloop end ensure File.unlink(@socket) if @socket @ios.each{ |io| io.close rescue nil } end end
[ "def", "run", "raise", "'Already running'", "if", "@running", "@stop", "=", "false", "@running", "=", "true", "begin", "until", "@stop", "mainloop", "end", "ensure", "File", ".", "unlink", "(", "@socket", ")", "if", "@socket", "@ios", ".", "each", "{", "|", "io", "|", "io", ".", "close", "rescue", "nil", "}", "end", "end" ]
Run the server @note This method blocks!
[ "Run", "the", "server" ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/server.rb#L28-L40
train
jeremyevans/erubi
lib/erubi/capture_end.rb
Erubi.CaptureEndEngine.handle
def handle(indicator, code, tailch, rspace, lspace) case indicator when '|=', '|==' rspace = nil if tailch && !tailch.empty? add_text(lspace) if lspace escape_capture = !((indicator == '|=') ^ @escape_capture) src << "begin; (#{@bufstack} ||= []) << #{@bufvar}; #{@bufvar} = #{@bufval}; #{@bufstack}.last << #{@escapefunc if escape_capture}((" << code add_text(rspace) if rspace when '|' rspace = nil if tailch && !tailch.empty? add_text(lspace) if lspace result = @yield_returns_buffer ? " #{@bufvar}; " : "" src << result << code << ")).to_s; ensure; #{@bufvar} = #{@bufstack}.pop; end;" add_text(rspace) if rspace else super end end
ruby
def handle(indicator, code, tailch, rspace, lspace) case indicator when '|=', '|==' rspace = nil if tailch && !tailch.empty? add_text(lspace) if lspace escape_capture = !((indicator == '|=') ^ @escape_capture) src << "begin; (#{@bufstack} ||= []) << #{@bufvar}; #{@bufvar} = #{@bufval}; #{@bufstack}.last << #{@escapefunc if escape_capture}((" << code add_text(rspace) if rspace when '|' rspace = nil if tailch && !tailch.empty? add_text(lspace) if lspace result = @yield_returns_buffer ? " #{@bufvar}; " : "" src << result << code << ")).to_s; ensure; #{@bufvar} = #{@bufstack}.pop; end;" add_text(rspace) if rspace else super end end
[ "def", "handle", "(", "indicator", ",", "code", ",", "tailch", ",", "rspace", ",", "lspace", ")", "case", "indicator", "when", "'|='", ",", "'|=='", "rspace", "=", "nil", "if", "tailch", "&&", "!", "tailch", ".", "empty?", "add_text", "(", "lspace", ")", "if", "lspace", "escape_capture", "=", "!", "(", "(", "indicator", "==", "'|='", ")", "^", "@escape_capture", ")", "src", "<<", "\"begin; (#{@bufstack} ||= []) << #{@bufvar}; #{@bufvar} = #{@bufval}; #{@bufstack}.last << #{@escapefunc if escape_capture}((\"", "<<", "code", "add_text", "(", "rspace", ")", "if", "rspace", "when", "'|'", "rspace", "=", "nil", "if", "tailch", "&&", "!", "tailch", ".", "empty?", "add_text", "(", "lspace", ")", "if", "lspace", "result", "=", "@yield_returns_buffer", "?", "\" #{@bufvar}; \"", ":", "\"\"", "src", "<<", "result", "<<", "code", "<<", "\")).to_s; ensure; #{@bufvar} = #{@bufstack}.pop; end;\"", "add_text", "(", "rspace", ")", "if", "rspace", "else", "super", "end", "end" ]
Handle the <%|= and <%|== tags
[ "Handle", "the", "<%|", "=", "and", "<%|", "==", "tags" ]
e33a64773990959e70f44046dab1f754c38deb54
https://github.com/jeremyevans/erubi/blob/e33a64773990959e70f44046dab1f754c38deb54/lib/erubi/capture_end.rb#L33-L50
train
chef/win32-certstore
lib/win32/certstore.rb
Win32.Certstore.open
def open(store_name) certstore_handler = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, nil, CERT_SYSTEM_STORE_LOCAL_MACHINE, wstring(store_name)) unless certstore_handler last_error = FFI::LastError.error raise SystemCallError.new("Unable to open the Certificate Store `#{store_name}`.", last_error) end add_finalizer(certstore_handler) certstore_handler end
ruby
def open(store_name) certstore_handler = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, nil, CERT_SYSTEM_STORE_LOCAL_MACHINE, wstring(store_name)) unless certstore_handler last_error = FFI::LastError.error raise SystemCallError.new("Unable to open the Certificate Store `#{store_name}`.", last_error) end add_finalizer(certstore_handler) certstore_handler end
[ "def", "open", "(", "store_name", ")", "certstore_handler", "=", "CertOpenStore", "(", "CERT_STORE_PROV_SYSTEM", ",", "0", ",", "nil", ",", "CERT_SYSTEM_STORE_LOCAL_MACHINE", ",", "wstring", "(", "store_name", ")", ")", "unless", "certstore_handler", "last_error", "=", "FFI", "::", "LastError", ".", "error", "raise", "SystemCallError", ".", "new", "(", "\"Unable to open the Certificate Store `#{store_name}`.\"", ",", "last_error", ")", "end", "add_finalizer", "(", "certstore_handler", ")", "certstore_handler", "end" ]
To open certstore and return open certificate store pointer
[ "To", "open", "certstore", "and", "return", "open", "certificate", "store", "pointer" ]
2fe520f7b235ee8c9aef780940cdb8f8c47f3b28
https://github.com/chef/win32-certstore/blob/2fe520f7b235ee8c9aef780940cdb8f8c47f3b28/lib/win32/certstore.rb#L120-L128
train
judofyr/temple
lib/temple/utils.rb
Temple.Utils.empty_exp?
def empty_exp?(exp) case exp[0] when :multi exp[1..-1].all? {|e| empty_exp?(e) } when :newline true else false end end
ruby
def empty_exp?(exp) case exp[0] when :multi exp[1..-1].all? {|e| empty_exp?(e) } when :newline true else false end end
[ "def", "empty_exp?", "(", "exp", ")", "case", "exp", "[", "0", "]", "when", ":multi", "exp", "[", "1", "..", "-", "1", "]", ".", "all?", "{", "|", "e", "|", "empty_exp?", "(", "e", ")", "}", "when", ":newline", "true", "else", "false", "end", "end" ]
Check if expression is empty @param exp [Array] Temple expression @return true if expression is empty
[ "Check", "if", "expression", "is", "empty" ]
7987ab67af00a598eb3d83192415371498a0f125
https://github.com/judofyr/temple/blob/7987ab67af00a598eb3d83192415371498a0f125/lib/temple/utils.rb#L76-L85
train
chef/mixlib-log
lib/mixlib/log.rb
Mixlib.Log.loggers_to_close
def loggers_to_close loggers_to_close = [] all_loggers.each do |logger| # unfortunately Logger does not provide access to the logdev # via public API. In order to reduce amount of impact and # handle only File type log devices I had to use this method # to get access to it. next unless (logdev = logger.instance_variable_get(:"@logdev")) loggers_to_close << logger if logdev.filename end loggers_to_close end
ruby
def loggers_to_close loggers_to_close = [] all_loggers.each do |logger| # unfortunately Logger does not provide access to the logdev # via public API. In order to reduce amount of impact and # handle only File type log devices I had to use this method # to get access to it. next unless (logdev = logger.instance_variable_get(:"@logdev")) loggers_to_close << logger if logdev.filename end loggers_to_close end
[ "def", "loggers_to_close", "loggers_to_close", "=", "[", "]", "all_loggers", ".", "each", "do", "|", "logger", "|", "# unfortunately Logger does not provide access to the logdev", "# via public API. In order to reduce amount of impact and", "# handle only File type log devices I had to use this method", "# to get access to it.", "next", "unless", "(", "logdev", "=", "logger", ".", "instance_variable_get", "(", ":\"", "\"", ")", ")", "loggers_to_close", "<<", "logger", "if", "logdev", ".", "filename", "end", "loggers_to_close", "end" ]
select all loggers with File log devices
[ "select", "all", "loggers", "with", "File", "log", "devices" ]
00dfe62ceb83a4a4ac1268622edb6e949b2fb0cf
https://github.com/chef/mixlib-log/blob/00dfe62ceb83a4a4ac1268622edb6e949b2fb0cf/lib/mixlib/log.rb#L186-L197
train
travis-ci/travis-core
spec/support/formats.rb
Support.Formats.normalize_json
def normalize_json(json) json = json.to_json unless json.is_a?(String) JSON.parse(json) end
ruby
def normalize_json(json) json = json.to_json unless json.is_a?(String) JSON.parse(json) end
[ "def", "normalize_json", "(", "json", ")", "json", "=", "json", ".", "to_json", "unless", "json", ".", "is_a?", "(", "String", ")", "JSON", ".", "parse", "(", "json", ")", "end" ]
normalizes datetime objects to strings etc. more similar to what the client would see.
[ "normalizes", "datetime", "objects", "to", "strings", "etc", ".", "more", "similar", "to", "what", "the", "client", "would", "see", "." ]
bf944c952724dd2f00ff0c466a5e217d10f73bea
https://github.com/travis-ci/travis-core/blob/bf944c952724dd2f00ff0c466a5e217d10f73bea/spec/support/formats.rb#L30-L33
train
travis-ci/travis-core
lib/travis/features.rb
Travis.Features.active?
def active?(feature, repository) feature_active?(feature) or (rollout.active?(feature, repository.owner) or repository_active?(feature, repository)) end
ruby
def active?(feature, repository) feature_active?(feature) or (rollout.active?(feature, repository.owner) or repository_active?(feature, repository)) end
[ "def", "active?", "(", "feature", ",", "repository", ")", "feature_active?", "(", "feature", ")", "or", "(", "rollout", ".", "active?", "(", "feature", ",", "repository", ".", "owner", ")", "or", "repository_active?", "(", "feature", ",", "repository", ")", ")", "end" ]
Returns whether a given feature is enabled either globally or for a given repository. By default, this will return false.
[ "Returns", "whether", "a", "given", "feature", "is", "enabled", "either", "globally", "or", "for", "a", "given", "repository", "." ]
bf944c952724dd2f00ff0c466a5e217d10f73bea
https://github.com/travis-ci/travis-core/blob/bf944c952724dd2f00ff0c466a5e217d10f73bea/lib/travis/features.rb#L26-L30
train
travis-ci/travis-core
lib/travis/features.rb
Travis.Features.owner_active?
def owner_active?(feature, owner) redis.sismember(owner_key(feature, owner), owner.id) end
ruby
def owner_active?(feature, owner) redis.sismember(owner_key(feature, owner), owner.id) end
[ "def", "owner_active?", "(", "feature", ",", "owner", ")", "redis", ".", "sismember", "(", "owner_key", "(", "feature", ",", "owner", ")", ",", "owner", ".", "id", ")", "end" ]
Return whether a feature has been enabled for a user. By default, this return false.
[ "Return", "whether", "a", "feature", "has", "been", "enabled", "for", "a", "user", "." ]
bf944c952724dd2f00ff0c466a5e217d10f73bea
https://github.com/travis-ci/travis-core/blob/bf944c952724dd2f00ff0c466a5e217d10f73bea/lib/travis/features.rb#L113-L115
train
travis-ci/travis-core
lib/travis/advisory_locks.rb
Travis.AdvisoryLocks.exclusive
def exclusive(timeout = 30) give_up_at = Time.now + timeout if timeout while timeout.nil? || Time.now < give_up_at do if obtained_lock? return yield else # Randomizing sleep time may help reduce contention. sleep(rand(0.1..0.2)) end end ensure release_lock unless transactional end
ruby
def exclusive(timeout = 30) give_up_at = Time.now + timeout if timeout while timeout.nil? || Time.now < give_up_at do if obtained_lock? return yield else # Randomizing sleep time may help reduce contention. sleep(rand(0.1..0.2)) end end ensure release_lock unless transactional end
[ "def", "exclusive", "(", "timeout", "=", "30", ")", "give_up_at", "=", "Time", ".", "now", "+", "timeout", "if", "timeout", "while", "timeout", ".", "nil?", "||", "Time", ".", "now", "<", "give_up_at", "do", "if", "obtained_lock?", "return", "yield", "else", "# Randomizing sleep time may help reduce contention.", "sleep", "(", "rand", "(", "0.1", "..", "0.2", ")", ")", "end", "end", "ensure", "release_lock", "unless", "transactional", "end" ]
must be used within a transaction
[ "must", "be", "used", "within", "a", "transaction" ]
bf944c952724dd2f00ff0c466a5e217d10f73bea
https://github.com/travis-ci/travis-core/blob/bf944c952724dd2f00ff0c466a5e217d10f73bea/lib/travis/advisory_locks.rb#L25-L37
train