id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
|---|---|---|---|---|---|---|---|---|---|---|---|
16,800
|
piotrmurach/finite_machine
|
lib/finite_machine/event_definition.rb
|
FiniteMachine.EventDefinition.apply
|
def apply(event_name, silent = false)
define_event_transition(event_name, silent)
define_event_bang(event_name, silent)
end
|
ruby
|
def apply(event_name, silent = false)
define_event_transition(event_name, silent)
define_event_bang(event_name, silent)
end
|
[
"def",
"apply",
"(",
"event_name",
",",
"silent",
"=",
"false",
")",
"define_event_transition",
"(",
"event_name",
",",
"silent",
")",
"define_event_bang",
"(",
"event_name",
",",
"silent",
")",
"end"
] |
Initialize an EventDefinition
@param [StateMachine] machine
@api private
Define transition event names as state machine events
@param [Symbol] event_name
the event name for which definition is created
@return [nil]
@api public
|
[
"Initialize",
"an",
"EventDefinition"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/event_definition.rb#L31-L34
|
16,801
|
piotrmurach/finite_machine
|
lib/finite_machine/event_definition.rb
|
FiniteMachine.EventDefinition.define_event_transition
|
def define_event_transition(event_name, silent)
machine.send(:define_singleton_method, event_name) do |*data, &block|
method = silent ? :transition : :trigger
machine.public_send(method, event_name, *data, &block)
end
end
|
ruby
|
def define_event_transition(event_name, silent)
machine.send(:define_singleton_method, event_name) do |*data, &block|
method = silent ? :transition : :trigger
machine.public_send(method, event_name, *data, &block)
end
end
|
[
"def",
"define_event_transition",
"(",
"event_name",
",",
"silent",
")",
"machine",
".",
"send",
"(",
":define_singleton_method",
",",
"event_name",
")",
"do",
"|",
"*",
"data",
",",
"&",
"block",
"|",
"method",
"=",
"silent",
"?",
":transition",
":",
":trigger",
"machine",
".",
"public_send",
"(",
"method",
",",
"event_name",
",",
"data",
",",
"block",
")",
"end",
"end"
] |
Define transition event
@param [Symbol] event_name
the event name
@param [Boolean] silent
if true don't trigger callbacks, otherwise do
@return [nil]
@api private
|
[
"Define",
"transition",
"event"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/event_definition.rb#L49-L54
|
16,802
|
piotrmurach/finite_machine
|
lib/finite_machine/dsl.rb
|
FiniteMachine.DSL.initial
|
def initial(value, **options)
state = (value && !value.is_a?(Hash)) ? value : raise_missing_state
name, @defer_initial, @silent_initial = *parse_initial(options)
@initial_event = name
event(name, FiniteMachine::DEFAULT_STATE => state, silent: @silent_initial)
end
|
ruby
|
def initial(value, **options)
state = (value && !value.is_a?(Hash)) ? value : raise_missing_state
name, @defer_initial, @silent_initial = *parse_initial(options)
@initial_event = name
event(name, FiniteMachine::DEFAULT_STATE => state, silent: @silent_initial)
end
|
[
"def",
"initial",
"(",
"value",
",",
"**",
"options",
")",
"state",
"=",
"(",
"value",
"&&",
"!",
"value",
".",
"is_a?",
"(",
"Hash",
")",
")",
"?",
"value",
":",
"raise_missing_state",
"name",
",",
"@defer_initial",
",",
"@silent_initial",
"=",
"parse_initial",
"(",
"options",
")",
"@initial_event",
"=",
"name",
"event",
"(",
"name",
",",
"FiniteMachine",
"::",
"DEFAULT_STATE",
"=>",
"state",
",",
"silent",
":",
"@silent_initial",
")",
"end"
] |
Initialize top level DSL
@api public
Define initial state
@param [Symbol] value
The initial state name.
@param [Hash[Symbol]] options
@option options [Symbol] :event
The event name.
@option options [Symbol] :defer
Set to true to defer initial state transition.
Default false.
@option options [Symbol] :silent
Set to true to disable callbacks.
Default true.
@example
initial :green
@example Defer initial event
initial state: green, defer: true
@example Trigger callbacks
initial :green, silent: false
@example Redefine event name
initial :green, event: :start
@param [String, Hash] value
@return [StateMachine]
@api public
|
[
"Initialize",
"top",
"level",
"DSL"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/dsl.rb#L99-L104
|
16,803
|
piotrmurach/finite_machine
|
lib/finite_machine/dsl.rb
|
FiniteMachine.DSL.event
|
def event(name, transitions = {}, &block)
detect_event_conflict!(name) if machine.auto_methods?
if block_given?
merger = ChoiceMerger.new(machine, name, transitions)
merger.instance_eval(&block)
else
transition_builder = TransitionBuilder.new(machine, name, transitions)
transition_builder.call(transitions)
end
end
|
ruby
|
def event(name, transitions = {}, &block)
detect_event_conflict!(name) if machine.auto_methods?
if block_given?
merger = ChoiceMerger.new(machine, name, transitions)
merger.instance_eval(&block)
else
transition_builder = TransitionBuilder.new(machine, name, transitions)
transition_builder.call(transitions)
end
end
|
[
"def",
"event",
"(",
"name",
",",
"transitions",
"=",
"{",
"}",
",",
"&",
"block",
")",
"detect_event_conflict!",
"(",
"name",
")",
"if",
"machine",
".",
"auto_methods?",
"if",
"block_given?",
"merger",
"=",
"ChoiceMerger",
".",
"new",
"(",
"machine",
",",
"name",
",",
"transitions",
")",
"merger",
".",
"instance_eval",
"(",
"block",
")",
"else",
"transition_builder",
"=",
"TransitionBuilder",
".",
"new",
"(",
"machine",
",",
"name",
",",
"transitions",
")",
"transition_builder",
".",
"call",
"(",
"transitions",
")",
"end",
"end"
] |
Create event and associate transition
@example
event :go, :green => :yellow
event :go, :green => :yellow, if: :lights_on?
@param [Symbol] name
the event name
@param [Hash] transitions
the event transitions and conditions
@return [Transition]
@api public
|
[
"Create",
"event",
"and",
"associate",
"transition"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/dsl.rb#L142-L152
|
16,804
|
piotrmurach/finite_machine
|
lib/finite_machine/dsl.rb
|
FiniteMachine.DSL.parse_initial
|
def parse_initial(options)
[options.fetch(:event) { FiniteMachine::DEFAULT_EVENT_NAME },
options.fetch(:defer) { false },
options.fetch(:silent) { true }]
end
|
ruby
|
def parse_initial(options)
[options.fetch(:event) { FiniteMachine::DEFAULT_EVENT_NAME },
options.fetch(:defer) { false },
options.fetch(:silent) { true }]
end
|
[
"def",
"parse_initial",
"(",
"options",
")",
"[",
"options",
".",
"fetch",
"(",
":event",
")",
"{",
"FiniteMachine",
"::",
"DEFAULT_EVENT_NAME",
"}",
",",
"options",
".",
"fetch",
"(",
":defer",
")",
"{",
"false",
"}",
",",
"options",
".",
"fetch",
"(",
":silent",
")",
"{",
"true",
"}",
"]",
"end"
] |
Parse initial options
@param [Hash] options
the options to extract for initial state setup
@return [Array[Symbol,String]]
@api private
|
[
"Parse",
"initial",
"options"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/dsl.rb#L185-L189
|
16,805
|
piotrmurach/finite_machine
|
lib/finite_machine/state_machine.rb
|
FiniteMachine.StateMachine.is?
|
def is?(state)
if state.is_a?(Array)
state.include? current
else
state == current
end
end
|
ruby
|
def is?(state)
if state.is_a?(Array)
state.include? current
else
state == current
end
end
|
[
"def",
"is?",
"(",
"state",
")",
"if",
"state",
".",
"is_a?",
"(",
"Array",
")",
"state",
".",
"include?",
"current",
"else",
"state",
"==",
"current",
"end",
"end"
] |
Check if current state matches provided state
@example
fsm.is?(:green) # => true
@param [String, Array[String]] state
@return [Boolean]
@api public
|
[
"Check",
"if",
"current",
"state",
"matches",
"provided",
"state"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/state_machine.rb#L158-L164
|
16,806
|
piotrmurach/finite_machine
|
lib/finite_machine/state_machine.rb
|
FiniteMachine.StateMachine.can?
|
def can?(*args)
event_name = args.shift
events_map.can_perform?(event_name, current, *args)
end
|
ruby
|
def can?(*args)
event_name = args.shift
events_map.can_perform?(event_name, current, *args)
end
|
[
"def",
"can?",
"(",
"*",
"args",
")",
"event_name",
"=",
"args",
".",
"shift",
"events_map",
".",
"can_perform?",
"(",
"event_name",
",",
"current",
",",
"args",
")",
"end"
] |
Checks if event can be triggered
@example
fsm.can?(:go) # => true
@example
fsm.can?(:go, 'Piotr') # checks condition with parameter 'Piotr'
@param [String] event
@return [Boolean]
@api public
|
[
"Checks",
"if",
"event",
"can",
"be",
"triggered"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/state_machine.rb#L203-L206
|
16,807
|
piotrmurach/finite_machine
|
lib/finite_machine/state_machine.rb
|
FiniteMachine.StateMachine.valid_state?
|
def valid_state?(event_name)
current_states = events_map.states_for(event_name)
current_states.any? { |state| state == current || state == ANY_STATE }
end
|
ruby
|
def valid_state?(event_name)
current_states = events_map.states_for(event_name)
current_states.any? { |state| state == current || state == ANY_STATE }
end
|
[
"def",
"valid_state?",
"(",
"event_name",
")",
"current_states",
"=",
"events_map",
".",
"states_for",
"(",
"event_name",
")",
"current_states",
".",
"any?",
"{",
"|",
"state",
"|",
"state",
"==",
"current",
"||",
"state",
"==",
"ANY_STATE",
"}",
"end"
] |
Check if state is reachable
@param [Symbol] event_name
the event name for all transitions
@return [Boolean]
@api private
|
[
"Check",
"if",
"state",
"is",
"reachable"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/state_machine.rb#L250-L253
|
16,808
|
piotrmurach/finite_machine
|
lib/finite_machine/state_machine.rb
|
FiniteMachine.StateMachine.notify
|
def notify(hook_event_type, event_name, from, *data)
sync_shared do
hook_event = hook_event_type.build(current, event_name, from)
subscribers.visit(hook_event, *data)
end
end
|
ruby
|
def notify(hook_event_type, event_name, from, *data)
sync_shared do
hook_event = hook_event_type.build(current, event_name, from)
subscribers.visit(hook_event, *data)
end
end
|
[
"def",
"notify",
"(",
"hook_event_type",
",",
"event_name",
",",
"from",
",",
"*",
"data",
")",
"sync_shared",
"do",
"hook_event",
"=",
"hook_event_type",
".",
"build",
"(",
"current",
",",
"event_name",
",",
"from",
")",
"subscribers",
".",
"visit",
"(",
"hook_event",
",",
"data",
")",
"end",
"end"
] |
Notify about event all the subscribers
@param [HookEvent] :hook_event_type
The hook event type.
@param [FiniteMachine::Transition] :event_transition
The event transition.
@param [Array[Object]] :data
The data associated with the hook event.
@return [nil]
@api private
|
[
"Notify",
"about",
"event",
"all",
"the",
"subscribers"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/state_machine.rb#L267-L272
|
16,809
|
piotrmurach/finite_machine
|
lib/finite_machine/state_machine.rb
|
FiniteMachine.StateMachine.try_trigger
|
def try_trigger(event_name)
if valid_state?(event_name)
yield
else
exception = InvalidStateError
catch_error(exception) ||
fail(exception, "inappropriate current state '#{current}'")
false
end
end
|
ruby
|
def try_trigger(event_name)
if valid_state?(event_name)
yield
else
exception = InvalidStateError
catch_error(exception) ||
fail(exception, "inappropriate current state '#{current}'")
false
end
end
|
[
"def",
"try_trigger",
"(",
"event_name",
")",
"if",
"valid_state?",
"(",
"event_name",
")",
"yield",
"else",
"exception",
"=",
"InvalidStateError",
"catch_error",
"(",
"exception",
")",
"||",
"fail",
"(",
"exception",
",",
"\"inappropriate current state '#{current}'\"",
")",
"false",
"end",
"end"
] |
Attempt performing event trigger for valid state
@return [Boolean]
true is trigger successful, false otherwise
@api private
|
[
"Attempt",
"performing",
"event",
"trigger",
"for",
"valid",
"state"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/state_machine.rb#L280-L290
|
16,810
|
piotrmurach/finite_machine
|
lib/finite_machine/state_machine.rb
|
FiniteMachine.StateMachine.trigger!
|
def trigger!(event_name, *data, &block)
from = current # Save away current state
sync_exclusive do
notify HookEvent::Before, event_name, from, *data
status = try_trigger(event_name) do
if can?(event_name, *data)
notify HookEvent::Exit, event_name, from, *data
stat = transition!(event_name, *data, &block)
notify HookEvent::Transition, event_name, from, *data
notify HookEvent::Enter, event_name, from, *data
else
stat = false
end
stat
end
notify HookEvent::After, event_name, from, *data
status
end
rescue Exception => err
self.state = from # rollback transition
raise err
end
|
ruby
|
def trigger!(event_name, *data, &block)
from = current # Save away current state
sync_exclusive do
notify HookEvent::Before, event_name, from, *data
status = try_trigger(event_name) do
if can?(event_name, *data)
notify HookEvent::Exit, event_name, from, *data
stat = transition!(event_name, *data, &block)
notify HookEvent::Transition, event_name, from, *data
notify HookEvent::Enter, event_name, from, *data
else
stat = false
end
stat
end
notify HookEvent::After, event_name, from, *data
status
end
rescue Exception => err
self.state = from # rollback transition
raise err
end
|
[
"def",
"trigger!",
"(",
"event_name",
",",
"*",
"data",
",",
"&",
"block",
")",
"from",
"=",
"current",
"# Save away current state",
"sync_exclusive",
"do",
"notify",
"HookEvent",
"::",
"Before",
",",
"event_name",
",",
"from",
",",
"data",
"status",
"=",
"try_trigger",
"(",
"event_name",
")",
"do",
"if",
"can?",
"(",
"event_name",
",",
"data",
")",
"notify",
"HookEvent",
"::",
"Exit",
",",
"event_name",
",",
"from",
",",
"data",
"stat",
"=",
"transition!",
"(",
"event_name",
",",
"data",
",",
"block",
")",
"notify",
"HookEvent",
"::",
"Transition",
",",
"event_name",
",",
"from",
",",
"data",
"notify",
"HookEvent",
"::",
"Enter",
",",
"event_name",
",",
"from",
",",
"data",
"else",
"stat",
"=",
"false",
"end",
"stat",
"end",
"notify",
"HookEvent",
"::",
"After",
",",
"event_name",
",",
"from",
",",
"data",
"status",
"end",
"rescue",
"Exception",
"=>",
"err",
"self",
".",
"state",
"=",
"from",
"# rollback transition",
"raise",
"err",
"end"
] |
Trigger transition event with data
@param [Symbol] event_name
the event name
@param [Array] data
@return [Boolean]
true when transition is successful, false otherwise
@api public
|
[
"Trigger",
"transition",
"event",
"with",
"data"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/state_machine.rb#L302-L329
|
16,811
|
piotrmurach/finite_machine
|
lib/finite_machine/state_machine.rb
|
FiniteMachine.StateMachine.trigger
|
def trigger(event_name, *data, &block)
trigger!(event_name, *data, &block)
rescue InvalidStateError, TransitionError, CallbackError
false
end
|
ruby
|
def trigger(event_name, *data, &block)
trigger!(event_name, *data, &block)
rescue InvalidStateError, TransitionError, CallbackError
false
end
|
[
"def",
"trigger",
"(",
"event_name",
",",
"*",
"data",
",",
"&",
"block",
")",
"trigger!",
"(",
"event_name",
",",
"data",
",",
"block",
")",
"rescue",
"InvalidStateError",
",",
"TransitionError",
",",
"CallbackError",
"false",
"end"
] |
Trigger transition event without raising any errors
@param [Symbol] event_name
@return [Boolean]
true on successful transition, false otherwise
@api public
|
[
"Trigger",
"transition",
"event",
"without",
"raising",
"any",
"errors"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/state_machine.rb#L339-L343
|
16,812
|
piotrmurach/finite_machine
|
lib/finite_machine/state_machine.rb
|
FiniteMachine.StateMachine.transition!
|
def transition!(event_name, *data, &block)
from_state = current
to_state = events_map.move_to(event_name, from_state, *data)
block.call(from_state, to_state) if block
if log_transitions
Logger.report_transition(event_name, from_state, to_state, *data)
end
try_trigger(event_name) { transition_to!(to_state) }
end
|
ruby
|
def transition!(event_name, *data, &block)
from_state = current
to_state = events_map.move_to(event_name, from_state, *data)
block.call(from_state, to_state) if block
if log_transitions
Logger.report_transition(event_name, from_state, to_state, *data)
end
try_trigger(event_name) { transition_to!(to_state) }
end
|
[
"def",
"transition!",
"(",
"event_name",
",",
"*",
"data",
",",
"&",
"block",
")",
"from_state",
"=",
"current",
"to_state",
"=",
"events_map",
".",
"move_to",
"(",
"event_name",
",",
"from_state",
",",
"data",
")",
"block",
".",
"call",
"(",
"from_state",
",",
"to_state",
")",
"if",
"block",
"if",
"log_transitions",
"Logger",
".",
"report_transition",
"(",
"event_name",
",",
"from_state",
",",
"to_state",
",",
"data",
")",
"end",
"try_trigger",
"(",
"event_name",
")",
"{",
"transition_to!",
"(",
"to_state",
")",
"}",
"end"
] |
Find available state to transition to and transition
@param [Symbol] event_name
@api private
|
[
"Find",
"available",
"state",
"to",
"transition",
"to",
"and",
"transition"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/state_machine.rb#L350-L361
|
16,813
|
piotrmurach/finite_machine
|
lib/finite_machine/state_machine.rb
|
FiniteMachine.StateMachine.transition_to!
|
def transition_to!(new_state)
from_state = current
self.state = new_state
self.initial_state = new_state if from_state == DEFAULT_STATE
true
rescue Exception => e
catch_error(e) || raise_transition_error(e)
end
|
ruby
|
def transition_to!(new_state)
from_state = current
self.state = new_state
self.initial_state = new_state if from_state == DEFAULT_STATE
true
rescue Exception => e
catch_error(e) || raise_transition_error(e)
end
|
[
"def",
"transition_to!",
"(",
"new_state",
")",
"from_state",
"=",
"current",
"self",
".",
"state",
"=",
"new_state",
"self",
".",
"initial_state",
"=",
"new_state",
"if",
"from_state",
"==",
"DEFAULT_STATE",
"true",
"rescue",
"Exception",
"=>",
"e",
"catch_error",
"(",
"e",
")",
"||",
"raise_transition_error",
"(",
"e",
")",
"end"
] |
Update this state machine state to new one
@param [Symbol] new_state
@raise [TransitionError]
@api private
|
[
"Update",
"this",
"state",
"machine",
"state",
"to",
"new",
"one"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/state_machine.rb#L376-L383
|
16,814
|
piotrmurach/finite_machine
|
lib/finite_machine/state_machine.rb
|
FiniteMachine.StateMachine.method_missing
|
def method_missing(method_name, *args, &block)
if observer.respond_to?(method_name.to_sym)
observer.public_send(method_name.to_sym, *args, &block)
elsif env.aliases.include?(method_name.to_sym)
env.send(:target, *args, &block)
else
super
end
end
|
ruby
|
def method_missing(method_name, *args, &block)
if observer.respond_to?(method_name.to_sym)
observer.public_send(method_name.to_sym, *args, &block)
elsif env.aliases.include?(method_name.to_sym)
env.send(:target, *args, &block)
else
super
end
end
|
[
"def",
"method_missing",
"(",
"method_name",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"observer",
".",
"respond_to?",
"(",
"method_name",
".",
"to_sym",
")",
"observer",
".",
"public_send",
"(",
"method_name",
".",
"to_sym",
",",
"args",
",",
"block",
")",
"elsif",
"env",
".",
"aliases",
".",
"include?",
"(",
"method_name",
".",
"to_sym",
")",
"env",
".",
"send",
"(",
":target",
",",
"args",
",",
"block",
")",
"else",
"super",
"end",
"end"
] |
Forward the message to observer or self
@param [String] method_name
@param [Array] args
@return [self]
@api private
|
[
"Forward",
"the",
"message",
"to",
"observer",
"or",
"self"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/state_machine.rb#L421-L429
|
16,815
|
piotrmurach/finite_machine
|
lib/finite_machine/state_machine.rb
|
FiniteMachine.StateMachine.respond_to_missing?
|
def respond_to_missing?(method_name, include_private = false)
observer.respond_to?(method_name.to_sym) ||
env.aliases.include?(method_name.to_sym) || super
end
|
ruby
|
def respond_to_missing?(method_name, include_private = false)
observer.respond_to?(method_name.to_sym) ||
env.aliases.include?(method_name.to_sym) || super
end
|
[
"def",
"respond_to_missing?",
"(",
"method_name",
",",
"include_private",
"=",
"false",
")",
"observer",
".",
"respond_to?",
"(",
"method_name",
".",
"to_sym",
")",
"||",
"env",
".",
"aliases",
".",
"include?",
"(",
"method_name",
".",
"to_sym",
")",
"||",
"super",
"end"
] |
Test if a message can be handled by state machine
@param [String] method_name
@param [Boolean] include_private
@return [Boolean]
@api private
|
[
"Test",
"if",
"a",
"message",
"can",
"be",
"handled",
"by",
"state",
"machine"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/state_machine.rb#L440-L443
|
16,816
|
piotrmurach/finite_machine
|
lib/finite_machine/safety.rb
|
FiniteMachine.Safety.detect_event_conflict!
|
def detect_event_conflict!(event_name, method_name = event_name)
if method_already_implemented?(method_name)
raise FiniteMachine::AlreadyDefinedError, EVENT_CONFLICT_MESSAGE % {
name: event_name,
type: :instance,
method: method_name,
source: 'FiniteMachine'
}
end
end
|
ruby
|
def detect_event_conflict!(event_name, method_name = event_name)
if method_already_implemented?(method_name)
raise FiniteMachine::AlreadyDefinedError, EVENT_CONFLICT_MESSAGE % {
name: event_name,
type: :instance,
method: method_name,
source: 'FiniteMachine'
}
end
end
|
[
"def",
"detect_event_conflict!",
"(",
"event_name",
",",
"method_name",
"=",
"event_name",
")",
"if",
"method_already_implemented?",
"(",
"method_name",
")",
"raise",
"FiniteMachine",
"::",
"AlreadyDefinedError",
",",
"EVENT_CONFLICT_MESSAGE",
"%",
"{",
"name",
":",
"event_name",
",",
"type",
":",
":instance",
",",
"method",
":",
"method_name",
",",
"source",
":",
"'FiniteMachine'",
"}",
"end",
"end"
] |
Raise error when the method is already defined
@example
detect_event_conflict!(:test, "test=")
@raise [FiniteMachine::AlreadyDefinedError]
@return [nil]
@api public
|
[
"Raise",
"error",
"when",
"the",
"method",
"is",
"already",
"defined"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/safety.rb#L36-L45
|
16,817
|
piotrmurach/finite_machine
|
lib/finite_machine/safety.rb
|
FiniteMachine.Safety.ensure_valid_callback_name!
|
def ensure_valid_callback_name!(event_type, name)
message = if wrong_event_name?(name, event_type)
EVENT_CALLBACK_CONFLICT_MESSAGE % {
type: "on_#{event_type}",
name: name
}
elsif wrong_state_name?(name, event_type)
STATE_CALLBACK_CONFLICT_MESSAGE % {
type: "on_#{event_type}",
name: name
}
elsif !callback_names.include?(name)
CALLBACK_INVALID_MESSAGE % {
name: name,
callbacks: callback_names.to_a.inspect
}
else
nil
end
message && raise_invalid_callback_error(message)
end
|
ruby
|
def ensure_valid_callback_name!(event_type, name)
message = if wrong_event_name?(name, event_type)
EVENT_CALLBACK_CONFLICT_MESSAGE % {
type: "on_#{event_type}",
name: name
}
elsif wrong_state_name?(name, event_type)
STATE_CALLBACK_CONFLICT_MESSAGE % {
type: "on_#{event_type}",
name: name
}
elsif !callback_names.include?(name)
CALLBACK_INVALID_MESSAGE % {
name: name,
callbacks: callback_names.to_a.inspect
}
else
nil
end
message && raise_invalid_callback_error(message)
end
|
[
"def",
"ensure_valid_callback_name!",
"(",
"event_type",
",",
"name",
")",
"message",
"=",
"if",
"wrong_event_name?",
"(",
"name",
",",
"event_type",
")",
"EVENT_CALLBACK_CONFLICT_MESSAGE",
"%",
"{",
"type",
":",
"\"on_#{event_type}\"",
",",
"name",
":",
"name",
"}",
"elsif",
"wrong_state_name?",
"(",
"name",
",",
"event_type",
")",
"STATE_CALLBACK_CONFLICT_MESSAGE",
"%",
"{",
"type",
":",
"\"on_#{event_type}\"",
",",
"name",
":",
"name",
"}",
"elsif",
"!",
"callback_names",
".",
"include?",
"(",
"name",
")",
"CALLBACK_INVALID_MESSAGE",
"%",
"{",
"name",
":",
"name",
",",
"callbacks",
":",
"callback_names",
".",
"to_a",
".",
"inspect",
"}",
"else",
"nil",
"end",
"message",
"&&",
"raise_invalid_callback_error",
"(",
"message",
")",
"end"
] |
Raise error when the callback name is not valid
@example
ensure_valid_callback_name!(HookEvent::Enter, ":state_name")
@raise [FiniteMachine::InvalidCallbackNameError]
@return [nil]
@api public
|
[
"Raise",
"error",
"when",
"the",
"callback",
"name",
"is",
"not",
"valid"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/safety.rb#L57-L77
|
16,818
|
piotrmurach/finite_machine
|
lib/finite_machine/safety.rb
|
FiniteMachine.Safety.wrong_event_name?
|
def wrong_event_name?(name, event_type)
machine.states.include?(name) &&
!machine.events.include?(name) &&
event_type < HookEvent::Anyaction
end
|
ruby
|
def wrong_event_name?(name, event_type)
machine.states.include?(name) &&
!machine.events.include?(name) &&
event_type < HookEvent::Anyaction
end
|
[
"def",
"wrong_event_name?",
"(",
"name",
",",
"event_type",
")",
"machine",
".",
"states",
".",
"include?",
"(",
"name",
")",
"&&",
"!",
"machine",
".",
"events",
".",
"include?",
"(",
"name",
")",
"&&",
"event_type",
"<",
"HookEvent",
"::",
"Anyaction",
"end"
] |
Check if event name exists
@param [Symbol] name
@param [FiniteMachine::HookEvent] event_type
@return [Boolean]
@api private
|
[
"Check",
"if",
"event",
"name",
"exists"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/safety.rb#L90-L94
|
16,819
|
piotrmurach/finite_machine
|
lib/finite_machine/safety.rb
|
FiniteMachine.Safety.wrong_state_name?
|
def wrong_state_name?(name, event_type)
machine.events.include?(name) &&
!machine.states.include?(name) &&
event_type < HookEvent::Anystate
end
|
ruby
|
def wrong_state_name?(name, event_type)
machine.events.include?(name) &&
!machine.states.include?(name) &&
event_type < HookEvent::Anystate
end
|
[
"def",
"wrong_state_name?",
"(",
"name",
",",
"event_type",
")",
"machine",
".",
"events",
".",
"include?",
"(",
"name",
")",
"&&",
"!",
"machine",
".",
"states",
".",
"include?",
"(",
"name",
")",
"&&",
"event_type",
"<",
"HookEvent",
"::",
"Anystate",
"end"
] |
Check if state name exists
@param [Symbol] name
@param [FiniteMachine::HookEvent] event_type
@return [Boolean]
@api private
|
[
"Check",
"if",
"state",
"name",
"exists"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/safety.rb#L105-L109
|
16,820
|
piotrmurach/finite_machine
|
lib/finite_machine/message_queue.rb
|
FiniteMachine.MessageQueue.subscribe
|
def subscribe(*args, &block)
@mutex.synchronize do
listener = Listener.new(*args)
listener.on_delivery(&block)
@listeners << listener
end
end
|
ruby
|
def subscribe(*args, &block)
@mutex.synchronize do
listener = Listener.new(*args)
listener.on_delivery(&block)
@listeners << listener
end
end
|
[
"def",
"subscribe",
"(",
"*",
"args",
",",
"&",
"block",
")",
"@mutex",
".",
"synchronize",
"do",
"listener",
"=",
"Listener",
".",
"new",
"(",
"args",
")",
"listener",
".",
"on_delivery",
"(",
"block",
")",
"@listeners",
"<<",
"listener",
"end",
"end"
] |
Add listener to the queue to receive messages
@api public
|
[
"Add",
"listener",
"to",
"the",
"queue",
"to",
"receive",
"messages"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/message_queue.rb#L75-L81
|
16,821
|
piotrmurach/finite_machine
|
lib/finite_machine/message_queue.rb
|
FiniteMachine.MessageQueue.shutdown
|
def shutdown
fail EventQueueDeadError, 'event queue already dead' if @dead
queue = []
@mutex.synchronize do
@dead = true
@not_empty.broadcast
queue = @queue
@queue.clear
end
while !queue.empty?
discard_message(queue.pop)
end
true
end
|
ruby
|
def shutdown
fail EventQueueDeadError, 'event queue already dead' if @dead
queue = []
@mutex.synchronize do
@dead = true
@not_empty.broadcast
queue = @queue
@queue.clear
end
while !queue.empty?
discard_message(queue.pop)
end
true
end
|
[
"def",
"shutdown",
"fail",
"EventQueueDeadError",
",",
"'event queue already dead'",
"if",
"@dead",
"queue",
"=",
"[",
"]",
"@mutex",
".",
"synchronize",
"do",
"@dead",
"=",
"true",
"@not_empty",
".",
"broadcast",
"queue",
"=",
"@queue",
"@queue",
".",
"clear",
"end",
"while",
"!",
"queue",
".",
"empty?",
"discard_message",
"(",
"queue",
".",
"pop",
")",
"end",
"true",
"end"
] |
Shut down this event queue and clean it up
@example
event_queue.shutdown
@return [Boolean]
@api public
|
[
"Shut",
"down",
"this",
"event",
"queue",
"and",
"clean",
"it",
"up"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/message_queue.rb#L128-L143
|
16,822
|
piotrmurach/finite_machine
|
lib/finite_machine/message_queue.rb
|
FiniteMachine.MessageQueue.process_events
|
def process_events
until @dead
@mutex.synchronize do
while @queue.empty?
break if @dead
@not_empty.wait(@mutex)
end
event = @queue.pop
break unless event
notify_listeners(event)
event.dispatch
end
end
rescue Exception => ex
Logger.error "Error while running event: #{Logger.format_error(ex)}"
end
|
ruby
|
def process_events
until @dead
@mutex.synchronize do
while @queue.empty?
break if @dead
@not_empty.wait(@mutex)
end
event = @queue.pop
break unless event
notify_listeners(event)
event.dispatch
end
end
rescue Exception => ex
Logger.error "Error while running event: #{Logger.format_error(ex)}"
end
|
[
"def",
"process_events",
"until",
"@dead",
"@mutex",
".",
"synchronize",
"do",
"while",
"@queue",
".",
"empty?",
"break",
"if",
"@dead",
"@not_empty",
".",
"wait",
"(",
"@mutex",
")",
"end",
"event",
"=",
"@queue",
".",
"pop",
"break",
"unless",
"event",
"notify_listeners",
"(",
"event",
")",
"event",
".",
"dispatch",
"end",
"end",
"rescue",
"Exception",
"=>",
"ex",
"Logger",
".",
"error",
"\"Error while running event: #{Logger.format_error(ex)}\"",
"end"
] |
Process all the events
@return [Thread]
@api private
|
[
"Process",
"all",
"the",
"events"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/message_queue.rb#L179-L194
|
16,823
|
piotrmurach/finite_machine
|
lib/finite_machine/subscribers.rb
|
FiniteMachine.Subscribers.visit
|
def visit(hook_event, *data)
each { |subscriber|
synchronize { hook_event.notify(subscriber, *data) }
}
end
|
ruby
|
def visit(hook_event, *data)
each { |subscriber|
synchronize { hook_event.notify(subscriber, *data) }
}
end
|
[
"def",
"visit",
"(",
"hook_event",
",",
"*",
"data",
")",
"each",
"{",
"|",
"subscriber",
"|",
"synchronize",
"{",
"hook_event",
".",
"notify",
"(",
"subscriber",
",",
"data",
")",
"}",
"}",
"end"
] |
Visit subscribers and notify
@param [HookEvent] hook_event
the callback event to notify about
@return [undefined]
@api public
|
[
"Visit",
"subscribers",
"and",
"notify"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/subscribers.rb#L63-L67
|
16,824
|
piotrmurach/finite_machine
|
lib/finite_machine/transition_builder.rb
|
FiniteMachine.TransitionBuilder.call
|
def call(transitions)
StateParser.parse(transitions) do |from, to|
transition = Transition.new(@machine.env.target, @name,
@attributes.merge(states: { from => to }))
silent = @attributes.fetch(:silent, false)
@machine.events_map.add(@name, transition)
next unless @machine.auto_methods?
unless @machine.respond_to?(@name)
@event_definition.apply(@name, silent)
end
@state_definition.apply(from => to)
end
self
end
|
ruby
|
def call(transitions)
StateParser.parse(transitions) do |from, to|
transition = Transition.new(@machine.env.target, @name,
@attributes.merge(states: { from => to }))
silent = @attributes.fetch(:silent, false)
@machine.events_map.add(@name, transition)
next unless @machine.auto_methods?
unless @machine.respond_to?(@name)
@event_definition.apply(@name, silent)
end
@state_definition.apply(from => to)
end
self
end
|
[
"def",
"call",
"(",
"transitions",
")",
"StateParser",
".",
"parse",
"(",
"transitions",
")",
"do",
"|",
"from",
",",
"to",
"|",
"transition",
"=",
"Transition",
".",
"new",
"(",
"@machine",
".",
"env",
".",
"target",
",",
"@name",
",",
"@attributes",
".",
"merge",
"(",
"states",
":",
"{",
"from",
"=>",
"to",
"}",
")",
")",
"silent",
"=",
"@attributes",
".",
"fetch",
"(",
":silent",
",",
"false",
")",
"@machine",
".",
"events_map",
".",
"add",
"(",
"@name",
",",
"transition",
")",
"next",
"unless",
"@machine",
".",
"auto_methods?",
"unless",
"@machine",
".",
"respond_to?",
"(",
"@name",
")",
"@event_definition",
".",
"apply",
"(",
"@name",
",",
"silent",
")",
"end",
"@state_definition",
".",
"apply",
"(",
"from",
"=>",
"to",
")",
"end",
"self",
"end"
] |
Initialize a TransitionBuilder
@example
TransitionBuilder.new(machine, {})
@api public
Converts user transitions into internal {Transition} representation
@example
transition_builder.call([:green, :yellow] => :red)
@param [Hash[Symbol]] transitions
The transitions to extract states from
@return [self]
@api public
|
[
"Initialize",
"a",
"TransitionBuilder"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/transition_builder.rb#L41-L55
|
16,825
|
piotrmurach/finite_machine
|
lib/finite_machine/catchable.rb
|
FiniteMachine.Catchable.handle
|
def handle(*exceptions, &block)
options = exceptions.last.is_a?(Hash) ? exceptions.pop : {}
unless options.key?(:with)
if block_given?
options[:with] = block
else
raise ArgumentError, 'Need to provide error handler.'
end
end
evaluate_exceptions(exceptions, options)
end
|
ruby
|
def handle(*exceptions, &block)
options = exceptions.last.is_a?(Hash) ? exceptions.pop : {}
unless options.key?(:with)
if block_given?
options[:with] = block
else
raise ArgumentError, 'Need to provide error handler.'
end
end
evaluate_exceptions(exceptions, options)
end
|
[
"def",
"handle",
"(",
"*",
"exceptions",
",",
"&",
"block",
")",
"options",
"=",
"exceptions",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"exceptions",
".",
"pop",
":",
"{",
"}",
"unless",
"options",
".",
"key?",
"(",
":with",
")",
"if",
"block_given?",
"options",
"[",
":with",
"]",
"=",
"block",
"else",
"raise",
"ArgumentError",
",",
"'Need to provide error handler.'",
"end",
"end",
"evaluate_exceptions",
"(",
"exceptions",
",",
"options",
")",
"end"
] |
Rescue exception raised in state machine
@param [Array[Exception]] exceptions
@example
handle TransitionError, with: :pretty_errors
@example
handle TransitionError do |exception|
logger.info exception.message
raise exception
end
@api public
|
[
"Rescue",
"exception",
"raised",
"in",
"state",
"machine"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/catchable.rb#L29-L40
|
16,826
|
piotrmurach/finite_machine
|
lib/finite_machine/catchable.rb
|
FiniteMachine.Catchable.catch_error
|
def catch_error(exception)
if handler = handler_for_error(exception)
handler.arity.zero? ? handler.call : handler.call(exception)
true
end
end
|
ruby
|
def catch_error(exception)
if handler = handler_for_error(exception)
handler.arity.zero? ? handler.call : handler.call(exception)
true
end
end
|
[
"def",
"catch_error",
"(",
"exception",
")",
"if",
"handler",
"=",
"handler_for_error",
"(",
"exception",
")",
"handler",
".",
"arity",
".",
"zero?",
"?",
"handler",
".",
"call",
":",
"handler",
".",
"call",
"(",
"exception",
")",
"true",
"end",
"end"
] |
Catches error and finds a handler
@param [Exception] exception
@return [Boolean]
true if handler is found, nil otherwise
@api public
|
[
"Catches",
"error",
"and",
"finds",
"a",
"handler"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/catchable.rb#L50-L55
|
16,827
|
piotrmurach/finite_machine
|
lib/finite_machine/catchable.rb
|
FiniteMachine.Catchable.extract_const
|
def extract_const(class_name)
class_name.split('::').reduce(FiniteMachine) do |constant, part|
constant.const_get(part)
end
end
|
ruby
|
def extract_const(class_name)
class_name.split('::').reduce(FiniteMachine) do |constant, part|
constant.const_get(part)
end
end
|
[
"def",
"extract_const",
"(",
"class_name",
")",
"class_name",
".",
"split",
"(",
"'::'",
")",
".",
"reduce",
"(",
"FiniteMachine",
")",
"do",
"|",
"constant",
",",
"part",
"|",
"constant",
".",
"const_get",
"(",
"part",
")",
"end",
"end"
] |
Find constant in state machine namespace
@param [String] class_name
@api private
|
[
"Find",
"constant",
"in",
"state",
"machine",
"namespace"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/catchable.rb#L73-L77
|
16,828
|
piotrmurach/finite_machine
|
lib/finite_machine/catchable.rb
|
FiniteMachine.Catchable.evaluate_handler
|
def evaluate_handler(handler)
case handler
when Symbol
target.method(handler)
when Proc
if handler.arity.zero?
proc { instance_exec(&handler) }
else
proc { |_exception| instance_exec(_exception, &handler) }
end
end
end
|
ruby
|
def evaluate_handler(handler)
case handler
when Symbol
target.method(handler)
when Proc
if handler.arity.zero?
proc { instance_exec(&handler) }
else
proc { |_exception| instance_exec(_exception, &handler) }
end
end
end
|
[
"def",
"evaluate_handler",
"(",
"handler",
")",
"case",
"handler",
"when",
"Symbol",
"target",
".",
"method",
"(",
"handler",
")",
"when",
"Proc",
"if",
"handler",
".",
"arity",
".",
"zero?",
"proc",
"{",
"instance_exec",
"(",
"handler",
")",
"}",
"else",
"proc",
"{",
"|",
"_exception",
"|",
"instance_exec",
"(",
"_exception",
",",
"handler",
")",
"}",
"end",
"end",
"end"
] |
Executes given handler
@api private
|
[
"Executes",
"given",
"handler"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/catchable.rb#L82-L93
|
16,829
|
piotrmurach/finite_machine
|
lib/finite_machine/catchable.rb
|
FiniteMachine.Catchable.evaluate_exceptions
|
def evaluate_exceptions(exceptions, options)
exceptions.each do |exception|
key = if exception.is_a?(Class) && exception <= Exception
exception.name
elsif exception.is_a?(String)
exception
else
raise ArgumentError, "#{exception} isn't an Exception"
end
error_handlers << [key, options[:with]]
end
end
|
ruby
|
def evaluate_exceptions(exceptions, options)
exceptions.each do |exception|
key = if exception.is_a?(Class) && exception <= Exception
exception.name
elsif exception.is_a?(String)
exception
else
raise ArgumentError, "#{exception} isn't an Exception"
end
error_handlers << [key, options[:with]]
end
end
|
[
"def",
"evaluate_exceptions",
"(",
"exceptions",
",",
"options",
")",
"exceptions",
".",
"each",
"do",
"|",
"exception",
"|",
"key",
"=",
"if",
"exception",
".",
"is_a?",
"(",
"Class",
")",
"&&",
"exception",
"<=",
"Exception",
"exception",
".",
"name",
"elsif",
"exception",
".",
"is_a?",
"(",
"String",
")",
"exception",
"else",
"raise",
"ArgumentError",
",",
"\"#{exception} isn't an Exception\"",
"end",
"error_handlers",
"<<",
"[",
"key",
",",
"options",
"[",
":with",
"]",
"]",
"end",
"end"
] |
Check if exception inherits from Exception class and add to error handlers
@param [Array[Exception]] exceptions
@param [Hash] options
@api private
|
[
"Check",
"if",
"exception",
"inherits",
"from",
"Exception",
"class",
"and",
"add",
"to",
"error",
"handlers"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/catchable.rb#L102-L114
|
16,830
|
PagerDuty/lita-github
|
lib/lita-github/org.rb
|
LitaGithub.Org.team_id_by_slug
|
def team_id_by_slug(slug, org)
octo.organization_teams(org).each do |team|
return team[:id] if team[:slug] == slug.downcase
end
nil
end
|
ruby
|
def team_id_by_slug(slug, org)
octo.organization_teams(org).each do |team|
return team[:id] if team[:slug] == slug.downcase
end
nil
end
|
[
"def",
"team_id_by_slug",
"(",
"slug",
",",
"org",
")",
"octo",
".",
"organization_teams",
"(",
"org",
")",
".",
"each",
"do",
"|",
"team",
"|",
"return",
"team",
"[",
":id",
"]",
"if",
"team",
"[",
":slug",
"]",
"==",
"slug",
".",
"downcase",
"end",
"nil",
"end"
] |
Get the Github team ID using its slug
This depends on the `octo()` method from LitaGithub::Octo being within the same scope
@author Tim Heckman <tim@pagerduty.com>
@param slug [String] the slug of the team you're getting the ID for
@param org [String] the organization this team should belong in
@return [Nil] if no team was found nil is returned
@return [Integer] if a team is found the team's ID is returned
|
[
"Get",
"the",
"Github",
"team",
"ID",
"using",
"its",
"slug"
] |
3c3411e8daa4fbc3d5af506e159dd71c5ab6f48b
|
https://github.com/PagerDuty/lita-github/blob/3c3411e8daa4fbc3d5af506e159dd71c5ab6f48b/lib/lita-github/org.rb#L49-L54
|
16,831
|
PagerDuty/lita-github
|
lib/lita-github/org.rb
|
LitaGithub.Org.team_id
|
def team_id(team, org)
/^\d+$/.match(team.to_s) ? team : team_id_by_slug(team, org)
end
|
ruby
|
def team_id(team, org)
/^\d+$/.match(team.to_s) ? team : team_id_by_slug(team, org)
end
|
[
"def",
"team_id",
"(",
"team",
",",
"org",
")",
"/",
"\\d",
"/",
".",
"match",
"(",
"team",
".",
"to_s",
")",
"?",
"team",
":",
"team_id_by_slug",
"(",
"team",
",",
"org",
")",
"end"
] |
Get the team id based on either the team slug or the team id
@author Tim Heckman <tim@pagerduty.com>
@param team [String,Integer] this is either the team's slug or the team's id
@return [Integer] the team's id
|
[
"Get",
"the",
"team",
"id",
"based",
"on",
"either",
"the",
"team",
"slug",
"or",
"the",
"team",
"id"
] |
3c3411e8daa4fbc3d5af506e159dd71c5ab6f48b
|
https://github.com/PagerDuty/lita-github/blob/3c3411e8daa4fbc3d5af506e159dd71c5ab6f48b/lib/lita-github/org.rb#L61-L63
|
16,832
|
PagerDuty/lita-github
|
lib/lita-github/general.rb
|
LitaGithub.General.opts_parse
|
def opts_parse(cmd)
o = {}
cmd.scan(LitaGithub::R::OPT_REGEX).flatten.each do |opt|
k, v = symbolize_opt_key(*opt.strip.split(':'))
next if o.key?(k)
# if it looks like we're using the extended option (first character is a " or '):
# slice off the first and last character of the string
# otherwise:
# do nothing
v = v.slice!(1, (v.length - 2)) if %w(' ").include?(v.slice(0))
o[k] = to_i_if_numeric(v)
end
o
end
|
ruby
|
def opts_parse(cmd)
o = {}
cmd.scan(LitaGithub::R::OPT_REGEX).flatten.each do |opt|
k, v = symbolize_opt_key(*opt.strip.split(':'))
next if o.key?(k)
# if it looks like we're using the extended option (first character is a " or '):
# slice off the first and last character of the string
# otherwise:
# do nothing
v = v.slice!(1, (v.length - 2)) if %w(' ").include?(v.slice(0))
o[k] = to_i_if_numeric(v)
end
o
end
|
[
"def",
"opts_parse",
"(",
"cmd",
")",
"o",
"=",
"{",
"}",
"cmd",
".",
"scan",
"(",
"LitaGithub",
"::",
"R",
"::",
"OPT_REGEX",
")",
".",
"flatten",
".",
"each",
"do",
"|",
"opt",
"|",
"k",
",",
"v",
"=",
"symbolize_opt_key",
"(",
"opt",
".",
"strip",
".",
"split",
"(",
"':'",
")",
")",
"next",
"if",
"o",
".",
"key?",
"(",
"k",
")",
"# if it looks like we're using the extended option (first character is a \" or '):",
"# slice off the first and last character of the string",
"# otherwise:",
"# do nothing",
"v",
"=",
"v",
".",
"slice!",
"(",
"1",
",",
"(",
"v",
".",
"length",
"-",
"2",
")",
")",
"if",
"%w(",
"'",
"\"",
")",
".",
"include?",
"(",
"v",
".",
"slice",
"(",
"0",
")",
")",
"o",
"[",
"k",
"]",
"=",
"to_i_if_numeric",
"(",
"v",
")",
"end",
"o",
"end"
] |
Parse the options in the command using the option regex
@author Tim Heckman <tim@pagerduty.com>
@param cmd [String] the full command line provided to Lita
@return [Hash] the key:value pairs that were in the command string
|
[
"Parse",
"the",
"options",
"in",
"the",
"command",
"using",
"the",
"option",
"regex"
] |
3c3411e8daa4fbc3d5af506e159dd71c5ab6f48b
|
https://github.com/PagerDuty/lita-github/blob/3c3411e8daa4fbc3d5af506e159dd71c5ab6f48b/lib/lita-github/general.rb#L50-L65
|
16,833
|
PagerDuty/lita-github
|
lib/lita-github/repo.rb
|
LitaGithub.Repo.repo_has_team?
|
def repo_has_team?(full_name, team_id)
octo.repository_teams(full_name).each { |t| return true if t[:id] == team_id }
false
end
|
ruby
|
def repo_has_team?(full_name, team_id)
octo.repository_teams(full_name).each { |t| return true if t[:id] == team_id }
false
end
|
[
"def",
"repo_has_team?",
"(",
"full_name",
",",
"team_id",
")",
"octo",
".",
"repository_teams",
"(",
"full_name",
")",
".",
"each",
"{",
"|",
"t",
"|",
"return",
"true",
"if",
"t",
"[",
":id",
"]",
"==",
"team_id",
"}",
"false",
"end"
] |
Determine if the team is already on the repository
@param full_name [String] the canonical name of the repository
@param team_id [Integer] the id for the Github team
@return [TrueClass] if the team is already on the repo
@return [FalseClass] if the team is not on the repo
|
[
"Determine",
"if",
"the",
"team",
"is",
"already",
"on",
"the",
"repository"
] |
3c3411e8daa4fbc3d5af506e159dd71c5ab6f48b
|
https://github.com/PagerDuty/lita-github/blob/3c3411e8daa4fbc3d5af506e159dd71c5ab6f48b/lib/lita-github/repo.rb#L58-L61
|
16,834
|
jpmckinney/tf-idf-similarity
|
lib/tf-idf-similarity/extras/tf_idf_model.rb
|
TfIdfSimilarity.TfIdfModel.probabilistic_inverse_document_frequency
|
def probabilistic_inverse_document_frequency(term)
count = @model.document_count(term).to_f
log((documents.size - count) / count)
end
|
ruby
|
def probabilistic_inverse_document_frequency(term)
count = @model.document_count(term).to_f
log((documents.size - count) / count)
end
|
[
"def",
"probabilistic_inverse_document_frequency",
"(",
"term",
")",
"count",
"=",
"@model",
".",
"document_count",
"(",
"term",
")",
".",
"to_f",
"log",
"(",
"(",
"documents",
".",
"size",
"-",
"count",
")",
"/",
"count",
")",
"end"
] |
SMART p, Salton p, Chisholm IDFP
|
[
"SMART",
"p",
"Salton",
"p",
"Chisholm",
"IDFP"
] |
00777f8bee141aea3e22084c8257add7af0cbf5d
|
https://github.com/jpmckinney/tf-idf-similarity/blob/00777f8bee141aea3e22084c8257add7af0cbf5d/lib/tf-idf-similarity/extras/tf_idf_model.rb#L31-L34
|
16,835
|
jpmckinney/tf-idf-similarity
|
lib/tf-idf-similarity/extras/tf_idf_model.rb
|
TfIdfSimilarity.TfIdfModel.normalized_log_term_frequency
|
def normalized_log_term_frequency(document, term)
count = document.term_count(term)
if count > 0
(1 + log(count)) / (1 + log(document.average_term_count))
else
0
end
end
|
ruby
|
def normalized_log_term_frequency(document, term)
count = document.term_count(term)
if count > 0
(1 + log(count)) / (1 + log(document.average_term_count))
else
0
end
end
|
[
"def",
"normalized_log_term_frequency",
"(",
"document",
",",
"term",
")",
"count",
"=",
"document",
".",
"term_count",
"(",
"term",
")",
"if",
"count",
">",
"0",
"(",
"1",
"+",
"log",
"(",
"count",
")",
")",
"/",
"(",
"1",
"+",
"log",
"(",
"document",
".",
"average_term_count",
")",
")",
"else",
"0",
"end",
"end"
] |
SMART L, Chisholm LOGN
|
[
"SMART",
"L",
"Chisholm",
"LOGN"
] |
00777f8bee141aea3e22084c8257add7af0cbf5d
|
https://github.com/jpmckinney/tf-idf-similarity/blob/00777f8bee141aea3e22084c8257add7af0cbf5d/lib/tf-idf-similarity/extras/tf_idf_model.rb#L162-L169
|
16,836
|
jpmckinney/tf-idf-similarity
|
lib/tf-idf-similarity/document.rb
|
TfIdfSimilarity.Document.set_term_counts_and_size
|
def set_term_counts_and_size
tokenize(text).each do |word|
token = Token.new(word)
if token.valid?
term = token.lowercase_filter.classic_filter.to_s
@term_counts[term] += 1
@size += 1
end
end
end
|
ruby
|
def set_term_counts_and_size
tokenize(text).each do |word|
token = Token.new(word)
if token.valid?
term = token.lowercase_filter.classic_filter.to_s
@term_counts[term] += 1
@size += 1
end
end
end
|
[
"def",
"set_term_counts_and_size",
"tokenize",
"(",
"text",
")",
".",
"each",
"do",
"|",
"word",
"|",
"token",
"=",
"Token",
".",
"new",
"(",
"word",
")",
"if",
"token",
".",
"valid?",
"term",
"=",
"token",
".",
"lowercase_filter",
".",
"classic_filter",
".",
"to_s",
"@term_counts",
"[",
"term",
"]",
"+=",
"1",
"@size",
"+=",
"1",
"end",
"end",
"end"
] |
Tokenizes the text and counts terms and total tokens.
|
[
"Tokenizes",
"the",
"text",
"and",
"counts",
"terms",
"and",
"total",
"tokens",
"."
] |
00777f8bee141aea3e22084c8257add7af0cbf5d
|
https://github.com/jpmckinney/tf-idf-similarity/blob/00777f8bee141aea3e22084c8257add7af0cbf5d/lib/tf-idf-similarity/document.rb#L53-L62
|
16,837
|
jpmckinney/tf-idf-similarity
|
lib/tf-idf-similarity/bm25_model.rb
|
TfIdfSimilarity.BM25Model.inverse_document_frequency
|
def inverse_document_frequency(term)
df = @model.document_count(term)
log((documents.size - df + 0.5) / (df + 0.5))
end
|
ruby
|
def inverse_document_frequency(term)
df = @model.document_count(term)
log((documents.size - df + 0.5) / (df + 0.5))
end
|
[
"def",
"inverse_document_frequency",
"(",
"term",
")",
"df",
"=",
"@model",
".",
"document_count",
"(",
"term",
")",
"log",
"(",
"(",
"documents",
".",
"size",
"-",
"df",
"+",
"0.5",
")",
"/",
"(",
"df",
"+",
"0.5",
")",
")",
"end"
] |
Return the term's inverse document frequency.
@param [String] term a term
@return [Float] the term's inverse document frequency
|
[
"Return",
"the",
"term",
"s",
"inverse",
"document",
"frequency",
"."
] |
00777f8bee141aea3e22084c8257add7af0cbf5d
|
https://github.com/jpmckinney/tf-idf-similarity/blob/00777f8bee141aea3e22084c8257add7af0cbf5d/lib/tf-idf-similarity/bm25_model.rb#L11-L14
|
16,838
|
jpmckinney/tf-idf-similarity
|
lib/tf-idf-similarity/bm25_model.rb
|
TfIdfSimilarity.BM25Model.term_frequency
|
def term_frequency(document, term)
tf = document.term_count(term)
(tf * 2.2) / (tf + 0.3 + 0.9 * documents.size / @model.average_document_size)
end
|
ruby
|
def term_frequency(document, term)
tf = document.term_count(term)
(tf * 2.2) / (tf + 0.3 + 0.9 * documents.size / @model.average_document_size)
end
|
[
"def",
"term_frequency",
"(",
"document",
",",
"term",
")",
"tf",
"=",
"document",
".",
"term_count",
"(",
"term",
")",
"(",
"tf",
"*",
"2.2",
")",
"/",
"(",
"tf",
"+",
"0.3",
"+",
"0.9",
"*",
"documents",
".",
"size",
"/",
"@model",
".",
"average_document_size",
")",
"end"
] |
Returns the term's frequency in the document.
@param [Document] document a document
@param [String] term a term
@return [Float] the term's frequency in the document
@note Like Lucene, we use a b value of 0.75 and a k1 value of 1.2.
|
[
"Returns",
"the",
"term",
"s",
"frequency",
"in",
"the",
"document",
"."
] |
00777f8bee141aea3e22084c8257add7af0cbf5d
|
https://github.com/jpmckinney/tf-idf-similarity/blob/00777f8bee141aea3e22084c8257add7af0cbf5d/lib/tf-idf-similarity/bm25_model.rb#L24-L27
|
16,839
|
dry-rb/dry-view
|
lib/dry/view.rb
|
Dry.View.call
|
def call(format: config.default_format, context: config.default_context, **input)
ensure_config
env = self.class.render_env(format: format, context: context)
template_env = self.class.template_env(format: format, context: context)
locals = locals(template_env, input)
output = env.template(config.template, template_env.scope(config.scope, locals))
if layout?
layout_env = self.class.layout_env(format: format, context: context)
output = env.template(self.class.layout_path, layout_env.scope(config.scope, layout_locals(locals))) { output }
end
Rendered.new(output: output, locals: locals)
end
|
ruby
|
def call(format: config.default_format, context: config.default_context, **input)
ensure_config
env = self.class.render_env(format: format, context: context)
template_env = self.class.template_env(format: format, context: context)
locals = locals(template_env, input)
output = env.template(config.template, template_env.scope(config.scope, locals))
if layout?
layout_env = self.class.layout_env(format: format, context: context)
output = env.template(self.class.layout_path, layout_env.scope(config.scope, layout_locals(locals))) { output }
end
Rendered.new(output: output, locals: locals)
end
|
[
"def",
"call",
"(",
"format",
":",
"config",
".",
"default_format",
",",
"context",
":",
"config",
".",
"default_context",
",",
"**",
"input",
")",
"ensure_config",
"env",
"=",
"self",
".",
"class",
".",
"render_env",
"(",
"format",
":",
"format",
",",
"context",
":",
"context",
")",
"template_env",
"=",
"self",
".",
"class",
".",
"template_env",
"(",
"format",
":",
"format",
",",
"context",
":",
"context",
")",
"locals",
"=",
"locals",
"(",
"template_env",
",",
"input",
")",
"output",
"=",
"env",
".",
"template",
"(",
"config",
".",
"template",
",",
"template_env",
".",
"scope",
"(",
"config",
".",
"scope",
",",
"locals",
")",
")",
"if",
"layout?",
"layout_env",
"=",
"self",
".",
"class",
".",
"layout_env",
"(",
"format",
":",
"format",
",",
"context",
":",
"context",
")",
"output",
"=",
"env",
".",
"template",
"(",
"self",
".",
"class",
".",
"layout_path",
",",
"layout_env",
".",
"scope",
"(",
"config",
".",
"scope",
",",
"layout_locals",
"(",
"locals",
")",
")",
")",
"{",
"output",
"}",
"end",
"Rendered",
".",
"new",
"(",
"output",
":",
"output",
",",
"locals",
":",
"locals",
")",
"end"
] |
Render the view
@param format [Symbol] template format to use
@param context [Context] context object to use
@param input input data for preparing exposure values
@return [Rendered] rendered view object
@api public
|
[
"Render",
"the",
"view"
] |
477fe9e1f1f8e687c19d7c3a0ed15c0219a01821
|
https://github.com/dry-rb/dry-view/blob/477fe9e1f1f8e687c19d7c3a0ed15c0219a01821/lib/dry/view.rb#L459-L474
|
16,840
|
deep-cover/deep-cover
|
core_gem/spec/specs_tools.rb
|
DeepCover.CoveredCode.check_node_overlap!
|
def check_node_overlap!
node_to_positions = {}
each_node do |node|
node.proper_range.each do |position|
if node_to_positions[position]
already = node_to_positions[position]
puts "There is a proper_range overlap between #{node} and #{already}"
puts "Overlapping: #{already.proper_range & node.proper_range}"
binding.pry
end
node_to_positions[position] = node
end
end
end
|
ruby
|
def check_node_overlap!
node_to_positions = {}
each_node do |node|
node.proper_range.each do |position|
if node_to_positions[position]
already = node_to_positions[position]
puts "There is a proper_range overlap between #{node} and #{already}"
puts "Overlapping: #{already.proper_range & node.proper_range}"
binding.pry
end
node_to_positions[position] = node
end
end
end
|
[
"def",
"check_node_overlap!",
"node_to_positions",
"=",
"{",
"}",
"each_node",
"do",
"|",
"node",
"|",
"node",
".",
"proper_range",
".",
"each",
"do",
"|",
"position",
"|",
"if",
"node_to_positions",
"[",
"position",
"]",
"already",
"=",
"node_to_positions",
"[",
"position",
"]",
"puts",
"\"There is a proper_range overlap between #{node} and #{already}\"",
"puts",
"\"Overlapping: #{already.proper_range & node.proper_range}\"",
"binding",
".",
"pry",
"end",
"node_to_positions",
"[",
"position",
"]",
"=",
"node",
"end",
"end",
"end"
] |
For now, when an overlap is found, just open a binding.pry to make fixing it easier.
|
[
"For",
"now",
"when",
"an",
"overlap",
"is",
"found",
"just",
"open",
"a",
"binding",
".",
"pry",
"to",
"make",
"fixing",
"it",
"easier",
"."
] |
d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab
|
https://github.com/deep-cover/deep-cover/blob/d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab/core_gem/spec/specs_tools.rb#L82-L95
|
16,841
|
deep-cover/deep-cover
|
core_gem/lib/deep_cover/tools/content_tag.rb
|
DeepCover.Tools::ContentTag.content_tag
|
def content_tag(tag, content, **options)
attrs = options.map { |kind, value| %{ #{kind}="#{value}"} }.join
"<#{tag}#{attrs}>#{content}</#{tag}>"
end
|
ruby
|
def content_tag(tag, content, **options)
attrs = options.map { |kind, value| %{ #{kind}="#{value}"} }.join
"<#{tag}#{attrs}>#{content}</#{tag}>"
end
|
[
"def",
"content_tag",
"(",
"tag",
",",
"content",
",",
"**",
"options",
")",
"attrs",
"=",
"options",
".",
"map",
"{",
"|",
"kind",
",",
"value",
"|",
"%{ #{kind}=\"#{value}\"}",
"}",
".",
"join",
"\"<#{tag}#{attrs}>#{content}</#{tag}>\"",
"end"
] |
Poor man's content_tag. No HTML escaping included
|
[
"Poor",
"man",
"s",
"content_tag",
".",
"No",
"HTML",
"escaping",
"included"
] |
d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab
|
https://github.com/deep-cover/deep-cover/blob/d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab/core_gem/lib/deep_cover/tools/content_tag.rb#L6-L9
|
16,842
|
deep-cover/deep-cover
|
core_gem/spec/analyser/node_spec.rb
|
DeepCover.IgnoreNodes.results
|
def results(analyser)
r = analyser.results
[0, nil].map do |val|
r.select { |node, runs| runs == val }
.keys
.map(&:source)
end
end
|
ruby
|
def results(analyser)
r = analyser.results
[0, nil].map do |val|
r.select { |node, runs| runs == val }
.keys
.map(&:source)
end
end
|
[
"def",
"results",
"(",
"analyser",
")",
"r",
"=",
"analyser",
".",
"results",
"[",
"0",
",",
"nil",
"]",
".",
"map",
"do",
"|",
"val",
"|",
"r",
".",
"select",
"{",
"|",
"node",
",",
"runs",
"|",
"runs",
"==",
"val",
"}",
".",
"keys",
".",
"map",
"(",
":source",
")",
"end",
"end"
] |
returns not_covered, ignored
|
[
"returns",
"not_covered",
"ignored"
] |
d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab
|
https://github.com/deep-cover/deep-cover/blob/d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab/core_gem/spec/analyser/node_spec.rb#L35-L42
|
16,843
|
deep-cover/deep-cover
|
core_gem/lib/deep_cover/node/base.rb
|
DeepCover.Node.find_all
|
def find_all(lookup)
case lookup
when ::Module
each_node.grep(lookup)
when ::Symbol
each_node.find_all { |n| n.type == lookup }
when ::String
each_node.find_all { |n| n.source == lookup }
when ::Regexp
each_node.find_all { |n| n.source =~ lookup }
else
raise ::TypeError, "Expected class or symbol, got #{lookup.class}: #{lookup.inspect}"
end
end
|
ruby
|
def find_all(lookup)
case lookup
when ::Module
each_node.grep(lookup)
when ::Symbol
each_node.find_all { |n| n.type == lookup }
when ::String
each_node.find_all { |n| n.source == lookup }
when ::Regexp
each_node.find_all { |n| n.source =~ lookup }
else
raise ::TypeError, "Expected class or symbol, got #{lookup.class}: #{lookup.inspect}"
end
end
|
[
"def",
"find_all",
"(",
"lookup",
")",
"case",
"lookup",
"when",
"::",
"Module",
"each_node",
".",
"grep",
"(",
"lookup",
")",
"when",
"::",
"Symbol",
"each_node",
".",
"find_all",
"{",
"|",
"n",
"|",
"n",
".",
"type",
"==",
"lookup",
"}",
"when",
"::",
"String",
"each_node",
".",
"find_all",
"{",
"|",
"n",
"|",
"n",
".",
"source",
"==",
"lookup",
"}",
"when",
"::",
"Regexp",
"each_node",
".",
"find_all",
"{",
"|",
"n",
"|",
"n",
".",
"source",
"=~",
"lookup",
"}",
"else",
"raise",
"::",
"TypeError",
",",
"\"Expected class or symbol, got #{lookup.class}: #{lookup.inspect}\"",
"end",
"end"
] |
Public API
Search self and descendants for a particular Class or type
|
[
"Public",
"API",
"Search",
"self",
"and",
"descendants",
"for",
"a",
"particular",
"Class",
"or",
"type"
] |
d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab
|
https://github.com/deep-cover/deep-cover/blob/d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab/core_gem/lib/deep_cover/node/base.rb#L39-L52
|
16,844
|
deep-cover/deep-cover
|
core_gem/lib/deep_cover/node/base.rb
|
DeepCover.Node.[]
|
def [](lookup)
if lookup.is_a?(Integer)
children.fetch(lookup)
else
found = find_all(lookup)
case found.size
when 1
found.first
when 0
raise "No children of type #{lookup}"
else
raise "Ambiguous lookup #{lookup}, found #{found}."
end
end
end
|
ruby
|
def [](lookup)
if lookup.is_a?(Integer)
children.fetch(lookup)
else
found = find_all(lookup)
case found.size
when 1
found.first
when 0
raise "No children of type #{lookup}"
else
raise "Ambiguous lookup #{lookup}, found #{found}."
end
end
end
|
[
"def",
"[]",
"(",
"lookup",
")",
"if",
"lookup",
".",
"is_a?",
"(",
"Integer",
")",
"children",
".",
"fetch",
"(",
"lookup",
")",
"else",
"found",
"=",
"find_all",
"(",
"lookup",
")",
"case",
"found",
".",
"size",
"when",
"1",
"found",
".",
"first",
"when",
"0",
"raise",
"\"No children of type #{lookup}\"",
"else",
"raise",
"\"Ambiguous lookup #{lookup}, found #{found}.\"",
"end",
"end",
"end"
] |
Shortcut to access children
|
[
"Shortcut",
"to",
"access",
"children"
] |
d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab
|
https://github.com/deep-cover/deep-cover/blob/d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab/core_gem/lib/deep_cover/node/base.rb#L55-L69
|
16,845
|
deep-cover/deep-cover
|
core_gem/lib/deep_cover/node/base.rb
|
DeepCover.Node.each_node
|
def each_node(&block)
return to_enum :each_node unless block_given?
children_nodes.each do |child|
child.each_node(&block)
end
yield self
self
end
|
ruby
|
def each_node(&block)
return to_enum :each_node unless block_given?
children_nodes.each do |child|
child.each_node(&block)
end
yield self
self
end
|
[
"def",
"each_node",
"(",
"&",
"block",
")",
"return",
"to_enum",
":each_node",
"unless",
"block_given?",
"children_nodes",
".",
"each",
"do",
"|",
"child",
"|",
"child",
".",
"each_node",
"(",
"block",
")",
"end",
"yield",
"self",
"self",
"end"
] |
Yields its children and itself
|
[
"Yields",
"its",
"children",
"and",
"itself"
] |
d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab
|
https://github.com/deep-cover/deep-cover/blob/d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab/core_gem/lib/deep_cover/node/base.rb#L122-L129
|
16,846
|
deep-cover/deep-cover
|
core_gem/lib/deep_cover/coverage.rb
|
DeepCover.Coverage.add_missing_covered_codes
|
def add_missing_covered_codes
top_level_path = DeepCover.config.paths.detect do |path|
next unless path.is_a?(String)
path = File.expand_path(path)
File.dirname(path) == path
end
if top_level_path
# One of the paths is a root path.
# Either a mistake, or the user wanted to check everything that gets loaded. Either way,
# we will probably hang from searching the files to load. (and then loading them, as there
# can be lots of ruby files) We prefer to warn the user and not do anything.
suggestion = "#{top_level_path}/**/*.rb"
warn ["Because the `paths` configured in DeepCover include #{top_level_path.inspect}, which is a root of your fs, ",
'DeepCover will not attempt to find Ruby files that were not required. Your coverage report will not include ',
'files that were not instrumented. This is to avoid extremely long wait times. If you actually want this to ',
"happen, then replace the specified `paths` with #{suggestion.inspect}.",
].join
return
end
DeepCover.all_tracked_file_paths.each do |path|
covered_code(path, tracker_hits: :zeroes)
end
nil
end
|
ruby
|
def add_missing_covered_codes
top_level_path = DeepCover.config.paths.detect do |path|
next unless path.is_a?(String)
path = File.expand_path(path)
File.dirname(path) == path
end
if top_level_path
# One of the paths is a root path.
# Either a mistake, or the user wanted to check everything that gets loaded. Either way,
# we will probably hang from searching the files to load. (and then loading them, as there
# can be lots of ruby files) We prefer to warn the user and not do anything.
suggestion = "#{top_level_path}/**/*.rb"
warn ["Because the `paths` configured in DeepCover include #{top_level_path.inspect}, which is a root of your fs, ",
'DeepCover will not attempt to find Ruby files that were not required. Your coverage report will not include ',
'files that were not instrumented. This is to avoid extremely long wait times. If you actually want this to ',
"happen, then replace the specified `paths` with #{suggestion.inspect}.",
].join
return
end
DeepCover.all_tracked_file_paths.each do |path|
covered_code(path, tracker_hits: :zeroes)
end
nil
end
|
[
"def",
"add_missing_covered_codes",
"top_level_path",
"=",
"DeepCover",
".",
"config",
".",
"paths",
".",
"detect",
"do",
"|",
"path",
"|",
"next",
"unless",
"path",
".",
"is_a?",
"(",
"String",
")",
"path",
"=",
"File",
".",
"expand_path",
"(",
"path",
")",
"File",
".",
"dirname",
"(",
"path",
")",
"==",
"path",
"end",
"if",
"top_level_path",
"# One of the paths is a root path.",
"# Either a mistake, or the user wanted to check everything that gets loaded. Either way,",
"# we will probably hang from searching the files to load. (and then loading them, as there",
"# can be lots of ruby files) We prefer to warn the user and not do anything.",
"suggestion",
"=",
"\"#{top_level_path}/**/*.rb\"",
"warn",
"[",
"\"Because the `paths` configured in DeepCover include #{top_level_path.inspect}, which is a root of your fs, \"",
",",
"'DeepCover will not attempt to find Ruby files that were not required. Your coverage report will not include '",
",",
"'files that were not instrumented. This is to avoid extremely long wait times. If you actually want this to '",
",",
"\"happen, then replace the specified `paths` with #{suggestion.inspect}.\"",
",",
"]",
".",
"join",
"return",
"end",
"DeepCover",
".",
"all_tracked_file_paths",
".",
"each",
"do",
"|",
"path",
"|",
"covered_code",
"(",
"path",
",",
"tracker_hits",
":",
":zeroes",
")",
"end",
"nil",
"end"
] |
If a file wasn't required, it won't be in the trackers. This adds those mossing files
|
[
"If",
"a",
"file",
"wasn",
"t",
"required",
"it",
"won",
"t",
"be",
"in",
"the",
"trackers",
".",
"This",
"adds",
"those",
"mossing",
"files"
] |
d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab
|
https://github.com/deep-cover/deep-cover/blob/d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab/core_gem/lib/deep_cover/coverage.rb#L60-L84
|
16,847
|
deep-cover/deep-cover
|
core_gem/lib/deep_cover/persistence.rb
|
top_level_module::DeepCover.Persistence.load_trackers
|
def load_trackers
tracker_hits_per_path_hashes = tracker_files.map do |full_path|
JSON.parse(full_path.binread).transform_keys(&:to_sym).yield_self do |version:, tracker_hits_per_path:|
raise "dump version mismatch: #{version}, currently #{VERSION}" unless version == VERSION
tracker_hits_per_path
end
end
self.class.merge_tracker_hits_per_paths(*tracker_hits_per_path_hashes)
end
|
ruby
|
def load_trackers
tracker_hits_per_path_hashes = tracker_files.map do |full_path|
JSON.parse(full_path.binread).transform_keys(&:to_sym).yield_self do |version:, tracker_hits_per_path:|
raise "dump version mismatch: #{version}, currently #{VERSION}" unless version == VERSION
tracker_hits_per_path
end
end
self.class.merge_tracker_hits_per_paths(*tracker_hits_per_path_hashes)
end
|
[
"def",
"load_trackers",
"tracker_hits_per_path_hashes",
"=",
"tracker_files",
".",
"map",
"do",
"|",
"full_path",
"|",
"JSON",
".",
"parse",
"(",
"full_path",
".",
"binread",
")",
".",
"transform_keys",
"(",
":to_sym",
")",
".",
"yield_self",
"do",
"|",
"version",
":",
",",
"tracker_hits_per_path",
":",
"|",
"raise",
"\"dump version mismatch: #{version}, currently #{VERSION}\"",
"unless",
"version",
"==",
"VERSION",
"tracker_hits_per_path",
"end",
"end",
"self",
".",
"class",
".",
"merge_tracker_hits_per_paths",
"(",
"tracker_hits_per_path_hashes",
")",
"end"
] |
returns a TrackerHitsPerPath
|
[
"returns",
"a",
"TrackerHitsPerPath"
] |
d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab
|
https://github.com/deep-cover/deep-cover/blob/d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab/core_gem/lib/deep_cover/persistence.rb#L32-L41
|
16,848
|
deep-cover/deep-cover
|
core_gem/lib/deep_cover/autoload_tracker.rb
|
DeepCover.AutoloadTracker.initialize_autoloaded_paths
|
def initialize_autoloaded_paths(mods = ObjectSpace.each_object(Module)) # &do_autoload_block
mods.each do |mod|
# Module's constants are shared with Object. But if you set autoloads directly on Module, they
# appear on multiple classes. So just skip, Object will take care of those.
next if mod == Module
# This happens with JRuby
next unless mod.respond_to?(:constants)
if mod.frozen?
if mod.constants.any? { |name| mod.autoload?(name) }
self.class.warn_frozen_module(mod)
end
next
end
mod.constants.each do |name|
# JRuby can talk about deprecated constants here
path = Tools.silence_warnings do
mod.autoload?(name)
end
next unless path
interceptor_path = setup_interceptor_for(mod, name, path)
yield mod, name, interceptor_path
end
end
end
|
ruby
|
def initialize_autoloaded_paths(mods = ObjectSpace.each_object(Module)) # &do_autoload_block
mods.each do |mod|
# Module's constants are shared with Object. But if you set autoloads directly on Module, they
# appear on multiple classes. So just skip, Object will take care of those.
next if mod == Module
# This happens with JRuby
next unless mod.respond_to?(:constants)
if mod.frozen?
if mod.constants.any? { |name| mod.autoload?(name) }
self.class.warn_frozen_module(mod)
end
next
end
mod.constants.each do |name|
# JRuby can talk about deprecated constants here
path = Tools.silence_warnings do
mod.autoload?(name)
end
next unless path
interceptor_path = setup_interceptor_for(mod, name, path)
yield mod, name, interceptor_path
end
end
end
|
[
"def",
"initialize_autoloaded_paths",
"(",
"mods",
"=",
"ObjectSpace",
".",
"each_object",
"(",
"Module",
")",
")",
"# &do_autoload_block",
"mods",
".",
"each",
"do",
"|",
"mod",
"|",
"# Module's constants are shared with Object. But if you set autoloads directly on Module, they",
"# appear on multiple classes. So just skip, Object will take care of those.",
"next",
"if",
"mod",
"==",
"Module",
"# This happens with JRuby",
"next",
"unless",
"mod",
".",
"respond_to?",
"(",
":constants",
")",
"if",
"mod",
".",
"frozen?",
"if",
"mod",
".",
"constants",
".",
"any?",
"{",
"|",
"name",
"|",
"mod",
".",
"autoload?",
"(",
"name",
")",
"}",
"self",
".",
"class",
".",
"warn_frozen_module",
"(",
"mod",
")",
"end",
"next",
"end",
"mod",
".",
"constants",
".",
"each",
"do",
"|",
"name",
"|",
"# JRuby can talk about deprecated constants here",
"path",
"=",
"Tools",
".",
"silence_warnings",
"do",
"mod",
".",
"autoload?",
"(",
"name",
")",
"end",
"next",
"unless",
"path",
"interceptor_path",
"=",
"setup_interceptor_for",
"(",
"mod",
",",
"name",
",",
"path",
")",
"yield",
"mod",
",",
"name",
",",
"interceptor_path",
"end",
"end",
"end"
] |
In JRuby, ObjectSpace.each_object is allowed for Module and Class, so we are good.
|
[
"In",
"JRuby",
"ObjectSpace",
".",
"each_object",
"is",
"allowed",
"for",
"Module",
"and",
"Class",
"so",
"we",
"are",
"good",
"."
] |
d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab
|
https://github.com/deep-cover/deep-cover/blob/d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab/core_gem/lib/deep_cover/autoload_tracker.rb#L79-L104
|
16,849
|
deep-cover/deep-cover
|
core_gem/lib/deep_cover/autoload_tracker.rb
|
DeepCover.AutoloadTracker.remove_interceptors
|
def remove_interceptors # &do_autoload_block
@autoloads_by_basename.each do |basename, entries|
entries.each do |entry|
mod = entry.mod_if_available
next unless mod
# Module's constants are shared with Object. But if you set autoloads directly on Module, they
# appear on multiple classes. So just skip, Object will take care of those.
next if mod == Module
yield mod, entry.name, entry.target_path
end
end
@autoloaded_paths = {}
@interceptor_files_by_path = {}
end
|
ruby
|
def remove_interceptors # &do_autoload_block
@autoloads_by_basename.each do |basename, entries|
entries.each do |entry|
mod = entry.mod_if_available
next unless mod
# Module's constants are shared with Object. But if you set autoloads directly on Module, they
# appear on multiple classes. So just skip, Object will take care of those.
next if mod == Module
yield mod, entry.name, entry.target_path
end
end
@autoloaded_paths = {}
@interceptor_files_by_path = {}
end
|
[
"def",
"remove_interceptors",
"# &do_autoload_block",
"@autoloads_by_basename",
".",
"each",
"do",
"|",
"basename",
",",
"entries",
"|",
"entries",
".",
"each",
"do",
"|",
"entry",
"|",
"mod",
"=",
"entry",
".",
"mod_if_available",
"next",
"unless",
"mod",
"# Module's constants are shared with Object. But if you set autoloads directly on Module, they",
"# appear on multiple classes. So just skip, Object will take care of those.",
"next",
"if",
"mod",
"==",
"Module",
"yield",
"mod",
",",
"entry",
".",
"name",
",",
"entry",
".",
"target_path",
"end",
"end",
"@autoloaded_paths",
"=",
"{",
"}",
"@interceptor_files_by_path",
"=",
"{",
"}",
"end"
] |
We need to remove the interceptor hooks, otherwise, the problem if manually requiring
something that is autoloaded will cause issues.
|
[
"We",
"need",
"to",
"remove",
"the",
"interceptor",
"hooks",
"otherwise",
"the",
"problem",
"if",
"manually",
"requiring",
"something",
"that",
"is",
"autoloaded",
"will",
"cause",
"issues",
"."
] |
d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab
|
https://github.com/deep-cover/deep-cover/blob/d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab/core_gem/lib/deep_cover/autoload_tracker.rb#L108-L122
|
16,850
|
deep-cover/deep-cover
|
core_gem/lib/deep_cover/tools/execute_sample.rb
|
DeepCover.Tools::ExecuteSample.execute_sample
|
def execute_sample(to_execute, source: nil)
# Disable some annoying warning by ruby. We are testing edge cases, so warnings are to be expected.
Tools.silence_warnings do
if to_execute.is_a?(CoveredCode)
to_execute.execute_code
else
to_execute.call
end
end
true
rescue StandardError => e
# In our samples, a simple `raise` is expected and doesn't need to be rescued
return false if e.is_a?(RuntimeError) && e.message.empty?
source = to_execute.covered_source if to_execute.is_a?(CoveredCode)
raise unless source
inner_msg = Tools.indent_string("#{e.class.name}: #{e.message}", 4)
source = Tools.indent_string(source, 4)
msg = "Exception when executing the sample:\n#{inner_msg}\n*Code follows*\n#{source}"
new_exc = ExceptionInSample.new(msg)
new_exc.set_backtrace(e.backtrace)
raise new_exc
end
|
ruby
|
def execute_sample(to_execute, source: nil)
# Disable some annoying warning by ruby. We are testing edge cases, so warnings are to be expected.
Tools.silence_warnings do
if to_execute.is_a?(CoveredCode)
to_execute.execute_code
else
to_execute.call
end
end
true
rescue StandardError => e
# In our samples, a simple `raise` is expected and doesn't need to be rescued
return false if e.is_a?(RuntimeError) && e.message.empty?
source = to_execute.covered_source if to_execute.is_a?(CoveredCode)
raise unless source
inner_msg = Tools.indent_string("#{e.class.name}: #{e.message}", 4)
source = Tools.indent_string(source, 4)
msg = "Exception when executing the sample:\n#{inner_msg}\n*Code follows*\n#{source}"
new_exc = ExceptionInSample.new(msg)
new_exc.set_backtrace(e.backtrace)
raise new_exc
end
|
[
"def",
"execute_sample",
"(",
"to_execute",
",",
"source",
":",
"nil",
")",
"# Disable some annoying warning by ruby. We are testing edge cases, so warnings are to be expected.",
"Tools",
".",
"silence_warnings",
"do",
"if",
"to_execute",
".",
"is_a?",
"(",
"CoveredCode",
")",
"to_execute",
".",
"execute_code",
"else",
"to_execute",
".",
"call",
"end",
"end",
"true",
"rescue",
"StandardError",
"=>",
"e",
"# In our samples, a simple `raise` is expected and doesn't need to be rescued",
"return",
"false",
"if",
"e",
".",
"is_a?",
"(",
"RuntimeError",
")",
"&&",
"e",
".",
"message",
".",
"empty?",
"source",
"=",
"to_execute",
".",
"covered_source",
"if",
"to_execute",
".",
"is_a?",
"(",
"CoveredCode",
")",
"raise",
"unless",
"source",
"inner_msg",
"=",
"Tools",
".",
"indent_string",
"(",
"\"#{e.class.name}: #{e.message}\"",
",",
"4",
")",
"source",
"=",
"Tools",
".",
"indent_string",
"(",
"source",
",",
"4",
")",
"msg",
"=",
"\"Exception when executing the sample:\\n#{inner_msg}\\n*Code follows*\\n#{source}\"",
"new_exc",
"=",
"ExceptionInSample",
".",
"new",
"(",
"msg",
")",
"new_exc",
".",
"set_backtrace",
"(",
"e",
".",
"backtrace",
")",
"raise",
"new_exc",
"end"
] |
Returns true if the code would have continued, false if the rescue was triggered.
|
[
"Returns",
"true",
"if",
"the",
"code",
"would",
"have",
"continued",
"false",
"if",
"the",
"rescue",
"was",
"triggered",
"."
] |
d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab
|
https://github.com/deep-cover/deep-cover/blob/d83c0b9f8d3dd59a28cdf81cf3ea1848eac77dab/core_gem/lib/deep_cover/tools/execute_sample.rb#L9-L32
|
16,851
|
chef/mixlib-config
|
lib/mixlib/config.rb
|
Mixlib.Config.from_file
|
def from_file(filename)
if %w{ .yml .yaml }.include?(File.extname(filename))
from_yaml(filename)
elsif File.extname(filename) == ".json"
from_json(filename)
elsif File.extname(filename) == ".toml"
from_toml(filename)
else
instance_eval(IO.read(filename), filename, 1)
end
end
|
ruby
|
def from_file(filename)
if %w{ .yml .yaml }.include?(File.extname(filename))
from_yaml(filename)
elsif File.extname(filename) == ".json"
from_json(filename)
elsif File.extname(filename) == ".toml"
from_toml(filename)
else
instance_eval(IO.read(filename), filename, 1)
end
end
|
[
"def",
"from_file",
"(",
"filename",
")",
"if",
"%w{",
".yml",
".yaml",
"}",
".",
"include?",
"(",
"File",
".",
"extname",
"(",
"filename",
")",
")",
"from_yaml",
"(",
"filename",
")",
"elsif",
"File",
".",
"extname",
"(",
"filename",
")",
"==",
"\".json\"",
"from_json",
"(",
"filename",
")",
"elsif",
"File",
".",
"extname",
"(",
"filename",
")",
"==",
"\".toml\"",
"from_toml",
"(",
"filename",
")",
"else",
"instance_eval",
"(",
"IO",
".",
"read",
"(",
"filename",
")",
",",
"filename",
",",
"1",
")",
"end",
"end"
] |
Loads a given ruby file, and runs instance_eval against it in the context of the current
object.
Raises an IOError if the file cannot be found, or is not readable.
=== Parameters
filename<String>:: A filename to read from
|
[
"Loads",
"a",
"given",
"ruby",
"file",
"and",
"runs",
"instance_eval",
"against",
"it",
"in",
"the",
"context",
"of",
"the",
"current",
"object",
"."
] |
039024aa606d2346235bfbb1c482a95d53c792ac
|
https://github.com/chef/mixlib-config/blob/039024aa606d2346235bfbb1c482a95d53c792ac/lib/mixlib/config.rb#L55-L65
|
16,852
|
chef/mixlib-config
|
lib/mixlib/config.rb
|
Mixlib.Config.reset
|
def reset
self.configuration = Hash.new
config_contexts.values.each { |config_context| config_context.reset }
end
|
ruby
|
def reset
self.configuration = Hash.new
config_contexts.values.each { |config_context| config_context.reset }
end
|
[
"def",
"reset",
"self",
".",
"configuration",
"=",
"Hash",
".",
"new",
"config_contexts",
".",
"values",
".",
"each",
"{",
"|",
"config_context",
"|",
"config_context",
".",
"reset",
"}",
"end"
] |
Resets all config options to their defaults.
|
[
"Resets",
"all",
"config",
"options",
"to",
"their",
"defaults",
"."
] |
039024aa606d2346235bfbb1c482a95d53c792ac
|
https://github.com/chef/mixlib-config/blob/039024aa606d2346235bfbb1c482a95d53c792ac/lib/mixlib/config.rb#L167-L170
|
16,853
|
chef/mixlib-config
|
lib/mixlib/config.rb
|
Mixlib.Config.save
|
def save(include_defaults = false)
result = configuration.dup
if include_defaults
(configurables.keys - result.keys).each do |missing_default|
# Ask any configurables to save themselves into the result array
if configurables[missing_default].has_default
result[missing_default] = configurables[missing_default].default
end
end
end
config_contexts.each_pair do |key, context|
context_result = context.save(include_defaults)
result[key] = context_result if context_result.size != 0 || include_defaults
end
config_context_lists.each_pair do |key, meta|
meta[:values].each do |context|
context_result = context.save(include_defaults)
result[key] = (result[key] || []) << context_result if context_result.size != 0 || include_defaults
end
end
config_context_hashes.each_pair do |key, meta|
meta[:values].each_pair do |context_key, context|
context_result = context.save(include_defaults)
(result[key] ||= {})[context_key] = context_result if context_result.size != 0 || include_defaults
end
end
result
end
|
ruby
|
def save(include_defaults = false)
result = configuration.dup
if include_defaults
(configurables.keys - result.keys).each do |missing_default|
# Ask any configurables to save themselves into the result array
if configurables[missing_default].has_default
result[missing_default] = configurables[missing_default].default
end
end
end
config_contexts.each_pair do |key, context|
context_result = context.save(include_defaults)
result[key] = context_result if context_result.size != 0 || include_defaults
end
config_context_lists.each_pair do |key, meta|
meta[:values].each do |context|
context_result = context.save(include_defaults)
result[key] = (result[key] || []) << context_result if context_result.size != 0 || include_defaults
end
end
config_context_hashes.each_pair do |key, meta|
meta[:values].each_pair do |context_key, context|
context_result = context.save(include_defaults)
(result[key] ||= {})[context_key] = context_result if context_result.size != 0 || include_defaults
end
end
result
end
|
[
"def",
"save",
"(",
"include_defaults",
"=",
"false",
")",
"result",
"=",
"configuration",
".",
"dup",
"if",
"include_defaults",
"(",
"configurables",
".",
"keys",
"-",
"result",
".",
"keys",
")",
".",
"each",
"do",
"|",
"missing_default",
"|",
"# Ask any configurables to save themselves into the result array",
"if",
"configurables",
"[",
"missing_default",
"]",
".",
"has_default",
"result",
"[",
"missing_default",
"]",
"=",
"configurables",
"[",
"missing_default",
"]",
".",
"default",
"end",
"end",
"end",
"config_contexts",
".",
"each_pair",
"do",
"|",
"key",
",",
"context",
"|",
"context_result",
"=",
"context",
".",
"save",
"(",
"include_defaults",
")",
"result",
"[",
"key",
"]",
"=",
"context_result",
"if",
"context_result",
".",
"size",
"!=",
"0",
"||",
"include_defaults",
"end",
"config_context_lists",
".",
"each_pair",
"do",
"|",
"key",
",",
"meta",
"|",
"meta",
"[",
":values",
"]",
".",
"each",
"do",
"|",
"context",
"|",
"context_result",
"=",
"context",
".",
"save",
"(",
"include_defaults",
")",
"result",
"[",
"key",
"]",
"=",
"(",
"result",
"[",
"key",
"]",
"||",
"[",
"]",
")",
"<<",
"context_result",
"if",
"context_result",
".",
"size",
"!=",
"0",
"||",
"include_defaults",
"end",
"end",
"config_context_hashes",
".",
"each_pair",
"do",
"|",
"key",
",",
"meta",
"|",
"meta",
"[",
":values",
"]",
".",
"each_pair",
"do",
"|",
"context_key",
",",
"context",
"|",
"context_result",
"=",
"context",
".",
"save",
"(",
"include_defaults",
")",
"(",
"result",
"[",
"key",
"]",
"||=",
"{",
"}",
")",
"[",
"context_key",
"]",
"=",
"context_result",
"if",
"context_result",
".",
"size",
"!=",
"0",
"||",
"include_defaults",
"end",
"end",
"result",
"end"
] |
Makes a copy of any non-default values.
This returns a shallow copy of the hash; while the hash itself is
duplicated a la dup, modifying data inside arrays and hashes may modify
the original Config object.
=== Returns
Hash of values the user has set.
=== Examples
For example, this config class:
class MyConfig < Mixlib::Config
default :will_be_set, 1
default :will_be_set_to_default, 1
default :will_not_be_set, 1
configurable(:computed_value) { |x| x*2 }
config_context :group do
default :will_not_be_set, 1
end
config_context :group_never_set
end
MyConfig.x = 2
MyConfig.will_be_set = 2
MyConfig.will_be_set_to_default = 1
MyConfig.computed_value = 2
MyConfig.group.x = 3
produces this:
MyConfig.save == {
:x => 2,
:will_be_set => 2,
:will_be_set_to_default => 1,
:computed_value => 4,
:group => {
:x => 3
}
}
|
[
"Makes",
"a",
"copy",
"of",
"any",
"non",
"-",
"default",
"values",
"."
] |
039024aa606d2346235bfbb1c482a95d53c792ac
|
https://github.com/chef/mixlib-config/blob/039024aa606d2346235bfbb1c482a95d53c792ac/lib/mixlib/config.rb#L215-L242
|
16,854
|
chef/mixlib-config
|
lib/mixlib/config.rb
|
Mixlib.Config.restore
|
def restore(hash)
self.configuration = hash.reject { |key, value| config_contexts.key?(key) }
config_contexts.each do |key, config_context|
if hash.key?(key)
config_context.restore(hash[key])
else
config_context.reset
end
end
config_context_lists.each do |key, meta|
meta[:values] = []
if hash.key?(key)
hash[key].each do |val|
context = define_context(meta[:definition_blocks])
context.restore(val)
meta[:values] << context
end
end
end
config_context_hashes.each do |key, meta|
meta[:values] = {}
if hash.key?(key)
hash[key].each do |vkey, val|
context = define_context(meta[:definition_blocks])
context.restore(val)
meta[:values][vkey] = context
end
end
end
end
|
ruby
|
def restore(hash)
self.configuration = hash.reject { |key, value| config_contexts.key?(key) }
config_contexts.each do |key, config_context|
if hash.key?(key)
config_context.restore(hash[key])
else
config_context.reset
end
end
config_context_lists.each do |key, meta|
meta[:values] = []
if hash.key?(key)
hash[key].each do |val|
context = define_context(meta[:definition_blocks])
context.restore(val)
meta[:values] << context
end
end
end
config_context_hashes.each do |key, meta|
meta[:values] = {}
if hash.key?(key)
hash[key].each do |vkey, val|
context = define_context(meta[:definition_blocks])
context.restore(val)
meta[:values][vkey] = context
end
end
end
end
|
[
"def",
"restore",
"(",
"hash",
")",
"self",
".",
"configuration",
"=",
"hash",
".",
"reject",
"{",
"|",
"key",
",",
"value",
"|",
"config_contexts",
".",
"key?",
"(",
"key",
")",
"}",
"config_contexts",
".",
"each",
"do",
"|",
"key",
",",
"config_context",
"|",
"if",
"hash",
".",
"key?",
"(",
"key",
")",
"config_context",
".",
"restore",
"(",
"hash",
"[",
"key",
"]",
")",
"else",
"config_context",
".",
"reset",
"end",
"end",
"config_context_lists",
".",
"each",
"do",
"|",
"key",
",",
"meta",
"|",
"meta",
"[",
":values",
"]",
"=",
"[",
"]",
"if",
"hash",
".",
"key?",
"(",
"key",
")",
"hash",
"[",
"key",
"]",
".",
"each",
"do",
"|",
"val",
"|",
"context",
"=",
"define_context",
"(",
"meta",
"[",
":definition_blocks",
"]",
")",
"context",
".",
"restore",
"(",
"val",
")",
"meta",
"[",
":values",
"]",
"<<",
"context",
"end",
"end",
"end",
"config_context_hashes",
".",
"each",
"do",
"|",
"key",
",",
"meta",
"|",
"meta",
"[",
":values",
"]",
"=",
"{",
"}",
"if",
"hash",
".",
"key?",
"(",
"key",
")",
"hash",
"[",
"key",
"]",
".",
"each",
"do",
"|",
"vkey",
",",
"val",
"|",
"context",
"=",
"define_context",
"(",
"meta",
"[",
":definition_blocks",
"]",
")",
"context",
".",
"restore",
"(",
"val",
")",
"meta",
"[",
":values",
"]",
"[",
"vkey",
"]",
"=",
"context",
"end",
"end",
"end",
"end"
] |
Restore non-default values from the given hash.
=== Parameters
hash<Hash>: a hash in the same format as output by save.
=== Returns
self
|
[
"Restore",
"non",
"-",
"default",
"values",
"from",
"the",
"given",
"hash",
"."
] |
039024aa606d2346235bfbb1c482a95d53c792ac
|
https://github.com/chef/mixlib-config/blob/039024aa606d2346235bfbb1c482a95d53c792ac/lib/mixlib/config.rb#L252-L281
|
16,855
|
chef/mixlib-config
|
lib/mixlib/config.rb
|
Mixlib.Config.merge!
|
def merge!(hash)
hash.each do |key, value|
if config_contexts.key?(key)
# Grab the config context and let internal_get cache it if so desired
config_contexts[key].restore(value)
else
configuration[key] = value
end
end
self
end
|
ruby
|
def merge!(hash)
hash.each do |key, value|
if config_contexts.key?(key)
# Grab the config context and let internal_get cache it if so desired
config_contexts[key].restore(value)
else
configuration[key] = value
end
end
self
end
|
[
"def",
"merge!",
"(",
"hash",
")",
"hash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"config_contexts",
".",
"key?",
"(",
"key",
")",
"# Grab the config context and let internal_get cache it if so desired",
"config_contexts",
"[",
"key",
"]",
".",
"restore",
"(",
"value",
")",
"else",
"configuration",
"[",
"key",
"]",
"=",
"value",
"end",
"end",
"self",
"end"
] |
Merge an incoming hash with our config options
=== Parameters
hash<Hash>: a hash in the same format as output by save.
=== Returns
self
|
[
"Merge",
"an",
"incoming",
"hash",
"with",
"our",
"config",
"options"
] |
039024aa606d2346235bfbb1c482a95d53c792ac
|
https://github.com/chef/mixlib-config/blob/039024aa606d2346235bfbb1c482a95d53c792ac/lib/mixlib/config.rb#L290-L300
|
16,856
|
chef/mixlib-config
|
lib/mixlib/config.rb
|
Mixlib.Config.config_context
|
def config_context(symbol, &block)
if configurables.key?(symbol)
raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{symbol} with a config context"
end
if config_contexts.key?(symbol)
context = config_contexts[symbol]
else
context = Class.new
context.extend(::Mixlib::Config)
context.config_parent = self
config_contexts[symbol] = context
define_attr_accessor_methods(symbol)
end
if block
context.instance_eval(&block)
end
context
end
|
ruby
|
def config_context(symbol, &block)
if configurables.key?(symbol)
raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{symbol} with a config context"
end
if config_contexts.key?(symbol)
context = config_contexts[symbol]
else
context = Class.new
context.extend(::Mixlib::Config)
context.config_parent = self
config_contexts[symbol] = context
define_attr_accessor_methods(symbol)
end
if block
context.instance_eval(&block)
end
context
end
|
[
"def",
"config_context",
"(",
"symbol",
",",
"&",
"block",
")",
"if",
"configurables",
".",
"key?",
"(",
"symbol",
")",
"raise",
"ReopenedConfigurableWithConfigContextError",
",",
"\"Cannot redefine config value #{symbol} with a config context\"",
"end",
"if",
"config_contexts",
".",
"key?",
"(",
"symbol",
")",
"context",
"=",
"config_contexts",
"[",
"symbol",
"]",
"else",
"context",
"=",
"Class",
".",
"new",
"context",
".",
"extend",
"(",
"::",
"Mixlib",
"::",
"Config",
")",
"context",
".",
"config_parent",
"=",
"self",
"config_contexts",
"[",
"symbol",
"]",
"=",
"context",
"define_attr_accessor_methods",
"(",
"symbol",
")",
"end",
"if",
"block",
"context",
".",
"instance_eval",
"(",
"block",
")",
"end",
"context",
"end"
] |
Allows you to create a new config context where you can define new
options with default values.
This method allows you to open up the configurable more than once.
For example:
config_context :server_info do
configurable(:url).defaults_to("http://localhost")
end
=== Parameters
symbol<Symbol>: the name of the context
block<Block>: a block that will be run in the context of this new config
class.
|
[
"Allows",
"you",
"to",
"create",
"a",
"new",
"config",
"context",
"where",
"you",
"can",
"define",
"new",
"options",
"with",
"default",
"values",
"."
] |
039024aa606d2346235bfbb1c482a95d53c792ac
|
https://github.com/chef/mixlib-config/blob/039024aa606d2346235bfbb1c482a95d53c792ac/lib/mixlib/config.rb#L399-L419
|
16,857
|
chef/mixlib-config
|
lib/mixlib/config.rb
|
Mixlib.Config.config_context_list
|
def config_context_list(plural_symbol, singular_symbol, &block)
if configurables.key?(plural_symbol)
raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{plural_symbol} with a config context"
end
unless config_context_lists.key?(plural_symbol)
config_context_lists[plural_symbol] = {
definition_blocks: [],
values: [],
}
define_list_attr_accessor_methods(plural_symbol, singular_symbol)
end
config_context_lists[plural_symbol][:definition_blocks] << block if block_given?
end
|
ruby
|
def config_context_list(plural_symbol, singular_symbol, &block)
if configurables.key?(plural_symbol)
raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{plural_symbol} with a config context"
end
unless config_context_lists.key?(plural_symbol)
config_context_lists[plural_symbol] = {
definition_blocks: [],
values: [],
}
define_list_attr_accessor_methods(plural_symbol, singular_symbol)
end
config_context_lists[plural_symbol][:definition_blocks] << block if block_given?
end
|
[
"def",
"config_context_list",
"(",
"plural_symbol",
",",
"singular_symbol",
",",
"&",
"block",
")",
"if",
"configurables",
".",
"key?",
"(",
"plural_symbol",
")",
"raise",
"ReopenedConfigurableWithConfigContextError",
",",
"\"Cannot redefine config value #{plural_symbol} with a config context\"",
"end",
"unless",
"config_context_lists",
".",
"key?",
"(",
"plural_symbol",
")",
"config_context_lists",
"[",
"plural_symbol",
"]",
"=",
"{",
"definition_blocks",
":",
"[",
"]",
",",
"values",
":",
"[",
"]",
",",
"}",
"define_list_attr_accessor_methods",
"(",
"plural_symbol",
",",
"singular_symbol",
")",
"end",
"config_context_lists",
"[",
"plural_symbol",
"]",
"[",
":definition_blocks",
"]",
"<<",
"block",
"if",
"block_given?",
"end"
] |
Allows you to create a new list of config contexts where you can define new
options with default values.
This method allows you to open up the configurable more than once.
For example:
config_context_list :listeners, :listener do
configurable(:url).defaults_to("http://localhost")
end
=== Parameters
symbol<Symbol>: the plural name for contexts in the list
symbol<Symbol>: the singular name for contexts in the list
block<Block>: a block that will be run in the context of this new config
class.
|
[
"Allows",
"you",
"to",
"create",
"a",
"new",
"list",
"of",
"config",
"contexts",
"where",
"you",
"can",
"define",
"new",
"options",
"with",
"default",
"values",
"."
] |
039024aa606d2346235bfbb1c482a95d53c792ac
|
https://github.com/chef/mixlib-config/blob/039024aa606d2346235bfbb1c482a95d53c792ac/lib/mixlib/config.rb#L437-L451
|
16,858
|
chef/mixlib-config
|
lib/mixlib/config.rb
|
Mixlib.Config.config_context_hash
|
def config_context_hash(plural_symbol, singular_symbol, &block)
if configurables.key?(plural_symbol)
raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{plural_symbol} with a config context"
end
unless config_context_hashes.key?(plural_symbol)
config_context_hashes[plural_symbol] = {
definition_blocks: [],
values: {},
}
define_hash_attr_accessor_methods(plural_symbol, singular_symbol)
end
config_context_hashes[plural_symbol][:definition_blocks] << block if block_given?
end
|
ruby
|
def config_context_hash(plural_symbol, singular_symbol, &block)
if configurables.key?(plural_symbol)
raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{plural_symbol} with a config context"
end
unless config_context_hashes.key?(plural_symbol)
config_context_hashes[plural_symbol] = {
definition_blocks: [],
values: {},
}
define_hash_attr_accessor_methods(plural_symbol, singular_symbol)
end
config_context_hashes[plural_symbol][:definition_blocks] << block if block_given?
end
|
[
"def",
"config_context_hash",
"(",
"plural_symbol",
",",
"singular_symbol",
",",
"&",
"block",
")",
"if",
"configurables",
".",
"key?",
"(",
"plural_symbol",
")",
"raise",
"ReopenedConfigurableWithConfigContextError",
",",
"\"Cannot redefine config value #{plural_symbol} with a config context\"",
"end",
"unless",
"config_context_hashes",
".",
"key?",
"(",
"plural_symbol",
")",
"config_context_hashes",
"[",
"plural_symbol",
"]",
"=",
"{",
"definition_blocks",
":",
"[",
"]",
",",
"values",
":",
"{",
"}",
",",
"}",
"define_hash_attr_accessor_methods",
"(",
"plural_symbol",
",",
"singular_symbol",
")",
"end",
"config_context_hashes",
"[",
"plural_symbol",
"]",
"[",
":definition_blocks",
"]",
"<<",
"block",
"if",
"block_given?",
"end"
] |
Allows you to create a new hash of config contexts where you can define new
options with default values.
This method allows you to open up the configurable more than once.
For example:
config_context_hash :listeners, :listener do
configurable(:url).defaults_to("http://localhost")
end
=== Parameters
symbol<Symbol>: the plural name for contexts in the list
symbol<Symbol>: the singular name for contexts in the list
block<Block>: a block that will be run in the context of this new config
class.
|
[
"Allows",
"you",
"to",
"create",
"a",
"new",
"hash",
"of",
"config",
"contexts",
"where",
"you",
"can",
"define",
"new",
"options",
"with",
"default",
"values",
"."
] |
039024aa606d2346235bfbb1c482a95d53c792ac
|
https://github.com/chef/mixlib-config/blob/039024aa606d2346235bfbb1c482a95d53c792ac/lib/mixlib/config.rb#L469-L483
|
16,859
|
chef/mixlib-config
|
lib/mixlib/config.rb
|
Mixlib.Config.internal_set
|
def internal_set(symbol, value)
if configurables.key?(symbol)
configurables[symbol].set(configuration, value)
elsif config_contexts.key?(symbol)
config_contexts[symbol].restore(value.to_hash)
else
if config_strict_mode == :warn
Chef::Log.warn("Setting unsupported config value #{symbol}.")
elsif config_strict_mode
raise UnknownConfigOptionError, "Cannot set unsupported config value #{symbol}."
end
configuration[symbol] = value
end
end
|
ruby
|
def internal_set(symbol, value)
if configurables.key?(symbol)
configurables[symbol].set(configuration, value)
elsif config_contexts.key?(symbol)
config_contexts[symbol].restore(value.to_hash)
else
if config_strict_mode == :warn
Chef::Log.warn("Setting unsupported config value #{symbol}.")
elsif config_strict_mode
raise UnknownConfigOptionError, "Cannot set unsupported config value #{symbol}."
end
configuration[symbol] = value
end
end
|
[
"def",
"internal_set",
"(",
"symbol",
",",
"value",
")",
"if",
"configurables",
".",
"key?",
"(",
"symbol",
")",
"configurables",
"[",
"symbol",
"]",
".",
"set",
"(",
"configuration",
",",
"value",
")",
"elsif",
"config_contexts",
".",
"key?",
"(",
"symbol",
")",
"config_contexts",
"[",
"symbol",
"]",
".",
"restore",
"(",
"value",
".",
"to_hash",
")",
"else",
"if",
"config_strict_mode",
"==",
":warn",
"Chef",
"::",
"Log",
".",
"warn",
"(",
"\"Setting unsupported config value #{symbol}.\"",
")",
"elsif",
"config_strict_mode",
"raise",
"UnknownConfigOptionError",
",",
"\"Cannot set unsupported config value #{symbol}.\"",
"end",
"configuration",
"[",
"symbol",
"]",
"=",
"value",
"end",
"end"
] |
Internal dispatch setter for config values.
=== Parameters
symbol<Symbol>:: Name of the method (variable setter)
value<Object>:: Value to be set in config hash
|
[
"Internal",
"dispatch",
"setter",
"for",
"config",
"values",
"."
] |
039024aa606d2346235bfbb1c482a95d53c792ac
|
https://github.com/chef/mixlib-config/blob/039024aa606d2346235bfbb1c482a95d53c792ac/lib/mixlib/config.rb#L606-L619
|
16,860
|
ryanb/nested_form
|
lib/nested_form/builder_mixin.rb
|
NestedForm.BuilderMixin.link_to_remove
|
def link_to_remove(*args, &block)
options = args.extract_options!.symbolize_keys
options[:class] = [options[:class], "remove_nested_fields"].compact.join(" ")
# Extracting "milestones" from "...[milestones_attributes][...]"
md = object_name.to_s.match /(\w+)_attributes\](?:\[[\w\d]+\])?$/
association = md && md[1]
options["data-association"] = association
args << (options.delete(:href) || "javascript:void(0)")
args << options
hidden_field(:_destroy) << @template.link_to(*args, &block)
end
|
ruby
|
def link_to_remove(*args, &block)
options = args.extract_options!.symbolize_keys
options[:class] = [options[:class], "remove_nested_fields"].compact.join(" ")
# Extracting "milestones" from "...[milestones_attributes][...]"
md = object_name.to_s.match /(\w+)_attributes\](?:\[[\w\d]+\])?$/
association = md && md[1]
options["data-association"] = association
args << (options.delete(:href) || "javascript:void(0)")
args << options
hidden_field(:_destroy) << @template.link_to(*args, &block)
end
|
[
"def",
"link_to_remove",
"(",
"*",
"args",
",",
"&",
"block",
")",
"options",
"=",
"args",
".",
"extract_options!",
".",
"symbolize_keys",
"options",
"[",
":class",
"]",
"=",
"[",
"options",
"[",
":class",
"]",
",",
"\"remove_nested_fields\"",
"]",
".",
"compact",
".",
"join",
"(",
"\" \"",
")",
"# Extracting \"milestones\" from \"...[milestones_attributes][...]\"",
"md",
"=",
"object_name",
".",
"to_s",
".",
"match",
"/",
"\\w",
"\\]",
"\\[",
"\\w",
"\\d",
"\\]",
"/",
"association",
"=",
"md",
"&&",
"md",
"[",
"1",
"]",
"options",
"[",
"\"data-association\"",
"]",
"=",
"association",
"args",
"<<",
"(",
"options",
".",
"delete",
"(",
":href",
")",
"||",
"\"javascript:void(0)\"",
")",
"args",
"<<",
"options",
"hidden_field",
"(",
":_destroy",
")",
"<<",
"@template",
".",
"link_to",
"(",
"args",
",",
"block",
")",
"end"
] |
Adds a link to remove the associated record. The first argment is the name of the link.
f.link_to_remove("Remove Task")
You can pass HTML options in a hash at the end and a block for the content.
<%= f.link_to_remove(:class => "remove_task", :href => "#") do %>
Remove Task
<% end %>
See the README for more details on where to call this method.
|
[
"Adds",
"a",
"link",
"to",
"remove",
"the",
"associated",
"record",
".",
"The",
"first",
"argment",
"is",
"the",
"name",
"of",
"the",
"link",
"."
] |
1b0689dfb4d230ceabd278eba159fcb02f23c68a
|
https://github.com/ryanb/nested_form/blob/1b0689dfb4d230ceabd278eba159fcb02f23c68a/lib/nested_form/builder_mixin.rb#L60-L72
|
16,861
|
noteflakes/lyp
|
lib/lyp/resolver.rb
|
Lyp.DependencyResolver.resolve_tree
|
def resolve_tree
permutations = permutate_simplified_tree
permutations = filter_invalid_permutations(permutations)
# select highest versioned dependencies (for those specified by user)
user_deps = tree.dependencies.keys
result = select_highest_versioned_permutation(permutations, user_deps).flatten
if result.empty? && !tree.dependencies.empty?
error("Failed to satisfy dependency requirements")
else
result
end
end
|
ruby
|
def resolve_tree
permutations = permutate_simplified_tree
permutations = filter_invalid_permutations(permutations)
# select highest versioned dependencies (for those specified by user)
user_deps = tree.dependencies.keys
result = select_highest_versioned_permutation(permutations, user_deps).flatten
if result.empty? && !tree.dependencies.empty?
error("Failed to satisfy dependency requirements")
else
result
end
end
|
[
"def",
"resolve_tree",
"permutations",
"=",
"permutate_simplified_tree",
"permutations",
"=",
"filter_invalid_permutations",
"(",
"permutations",
")",
"# select highest versioned dependencies (for those specified by user)",
"user_deps",
"=",
"tree",
".",
"dependencies",
".",
"keys",
"result",
"=",
"select_highest_versioned_permutation",
"(",
"permutations",
",",
"user_deps",
")",
".",
"flatten",
"if",
"result",
".",
"empty?",
"&&",
"!",
"tree",
".",
"dependencies",
".",
"empty?",
"error",
"(",
"\"Failed to satisfy dependency requirements\"",
")",
"else",
"result",
"end",
"end"
] |
Resolve the given dependency tree and return a list of concrete packages
that meet all dependency requirements.
The following stages are involved:
- Create permutations of possible version combinations for all dependencies
- Remove invalid permutations
- Select the permutation with the highest versions
|
[
"Resolve",
"the",
"given",
"dependency",
"tree",
"and",
"return",
"a",
"list",
"of",
"concrete",
"packages",
"that",
"meet",
"all",
"dependency",
"requirements",
"."
] |
cca29b702f65eb412cba50ba9d4e879e14930003
|
https://github.com/noteflakes/lyp/blob/cca29b702f65eb412cba50ba9d4e879e14930003/lib/lyp/resolver.rb#L108-L121
|
16,862
|
noteflakes/lyp
|
lib/lyp/resolver.rb
|
Lyp.DependencyResolver.dependencies_array
|
def dependencies_array(leaf, processed = {})
return processed[leaf] if processed[leaf]
deps_array = []
processed[leaf] = deps_array
leaf.each do |pack, versions|
a = []
versions.each do |version, deps|
perms = []
sub_perms = dependencies_array(deps, processed)
if sub_perms == []
perms += [version]
else
sub_perms[0].each do |perm|
perms << [version] + [perm].flatten
end
end
a += perms
end
deps_array << a
end
deps_array
end
|
ruby
|
def dependencies_array(leaf, processed = {})
return processed[leaf] if processed[leaf]
deps_array = []
processed[leaf] = deps_array
leaf.each do |pack, versions|
a = []
versions.each do |version, deps|
perms = []
sub_perms = dependencies_array(deps, processed)
if sub_perms == []
perms += [version]
else
sub_perms[0].each do |perm|
perms << [version] + [perm].flatten
end
end
a += perms
end
deps_array << a
end
deps_array
end
|
[
"def",
"dependencies_array",
"(",
"leaf",
",",
"processed",
"=",
"{",
"}",
")",
"return",
"processed",
"[",
"leaf",
"]",
"if",
"processed",
"[",
"leaf",
"]",
"deps_array",
"=",
"[",
"]",
"processed",
"[",
"leaf",
"]",
"=",
"deps_array",
"leaf",
".",
"each",
"do",
"|",
"pack",
",",
"versions",
"|",
"a",
"=",
"[",
"]",
"versions",
".",
"each",
"do",
"|",
"version",
",",
"deps",
"|",
"perms",
"=",
"[",
"]",
"sub_perms",
"=",
"dependencies_array",
"(",
"deps",
",",
"processed",
")",
"if",
"sub_perms",
"==",
"[",
"]",
"perms",
"+=",
"[",
"version",
"]",
"else",
"sub_perms",
"[",
"0",
"]",
".",
"each",
"do",
"|",
"perm",
"|",
"perms",
"<<",
"[",
"version",
"]",
"+",
"[",
"perm",
"]",
".",
"flatten",
"end",
"end",
"a",
"+=",
"perms",
"end",
"deps_array",
"<<",
"a",
"end",
"deps_array",
"end"
] |
Converts a simplified dependency tree into an array of dependencies,
containing a sub-array for each top-level dependency. Each such sub-array
contains, in its turn, version permutations for the top-level dependency
and any transitive dependencies.
|
[
"Converts",
"a",
"simplified",
"dependency",
"tree",
"into",
"an",
"array",
"of",
"dependencies",
"containing",
"a",
"sub",
"-",
"array",
"for",
"each",
"top",
"-",
"level",
"dependency",
".",
"Each",
"such",
"sub",
"-",
"array",
"contains",
"in",
"its",
"turn",
"version",
"permutations",
"for",
"the",
"top",
"-",
"level",
"dependency",
"and",
"any",
"transitive",
"dependencies",
"."
] |
cca29b702f65eb412cba50ba9d4e879e14930003
|
https://github.com/noteflakes/lyp/blob/cca29b702f65eb412cba50ba9d4e879e14930003/lib/lyp/resolver.rb#L317-L341
|
16,863
|
noteflakes/lyp
|
lib/lyp/resolver.rb
|
Lyp.DependencyResolver.filter_invalid_permutations
|
def filter_invalid_permutations(permutations)
valid = []
permutations.each do |perm|
versions = {}; invalid = false
perm.each do |ref|
if ref =~ /(.+)@(.+)/
name, version = $1, $2
if versions[name] && versions[name] != version
invalid = true
break
else
versions[name] = version
end
end
end
valid << perm.uniq unless invalid
end
valid
end
|
ruby
|
def filter_invalid_permutations(permutations)
valid = []
permutations.each do |perm|
versions = {}; invalid = false
perm.each do |ref|
if ref =~ /(.+)@(.+)/
name, version = $1, $2
if versions[name] && versions[name] != version
invalid = true
break
else
versions[name] = version
end
end
end
valid << perm.uniq unless invalid
end
valid
end
|
[
"def",
"filter_invalid_permutations",
"(",
"permutations",
")",
"valid",
"=",
"[",
"]",
"permutations",
".",
"each",
"do",
"|",
"perm",
"|",
"versions",
"=",
"{",
"}",
";",
"invalid",
"=",
"false",
"perm",
".",
"each",
"do",
"|",
"ref",
"|",
"if",
"ref",
"=~",
"/",
"/",
"name",
",",
"version",
"=",
"$1",
",",
"$2",
"if",
"versions",
"[",
"name",
"]",
"&&",
"versions",
"[",
"name",
"]",
"!=",
"version",
"invalid",
"=",
"true",
"break",
"else",
"versions",
"[",
"name",
"]",
"=",
"version",
"end",
"end",
"end",
"valid",
"<<",
"perm",
".",
"uniq",
"unless",
"invalid",
"end",
"valid",
"end"
] |
Remove invalid permutations, that is permutations that contain multiple
versions of the same package, a scenario which could arrive in the case of
circular dependencies, or when different dependencies rely on different
versions of the same transitive dependency.
|
[
"Remove",
"invalid",
"permutations",
"that",
"is",
"permutations",
"that",
"contain",
"multiple",
"versions",
"of",
"the",
"same",
"package",
"a",
"scenario",
"which",
"could",
"arrive",
"in",
"the",
"case",
"of",
"circular",
"dependencies",
"or",
"when",
"different",
"dependencies",
"rely",
"on",
"different",
"versions",
"of",
"the",
"same",
"transitive",
"dependency",
"."
] |
cca29b702f65eb412cba50ba9d4e879e14930003
|
https://github.com/noteflakes/lyp/blob/cca29b702f65eb412cba50ba9d4e879e14930003/lib/lyp/resolver.rb#L347-L366
|
16,864
|
noteflakes/lyp
|
lib/lyp/resolver.rb
|
Lyp.DependencyResolver.select_highest_versioned_permutation
|
def select_highest_versioned_permutation(permutations, user_deps)
sorted = sort_permutations(permutations, user_deps)
sorted.empty? ? [] : sorted.last
end
|
ruby
|
def select_highest_versioned_permutation(permutations, user_deps)
sorted = sort_permutations(permutations, user_deps)
sorted.empty? ? [] : sorted.last
end
|
[
"def",
"select_highest_versioned_permutation",
"(",
"permutations",
",",
"user_deps",
")",
"sorted",
"=",
"sort_permutations",
"(",
"permutations",
",",
"user_deps",
")",
"sorted",
".",
"empty?",
"?",
"[",
"]",
":",
"sorted",
".",
"last",
"end"
] |
Select the highest versioned permutation of package versions
|
[
"Select",
"the",
"highest",
"versioned",
"permutation",
"of",
"package",
"versions"
] |
cca29b702f65eb412cba50ba9d4e879e14930003
|
https://github.com/noteflakes/lyp/blob/cca29b702f65eb412cba50ba9d4e879e14930003/lib/lyp/resolver.rb#L369-L372
|
16,865
|
noteflakes/lyp
|
lib/lyp/resolver.rb
|
Lyp.DependencyResolver.sort_permutations
|
def sort_permutations(permutations, user_deps)
# Cache for versions converted to Gem::Version instances
versions = {}
map = lambda do |m, p|
if p =~ Lyp::PACKAGE_RE
m[$1] = versions[p] ||= (Lyp.version($2 || '0.0') rescue nil)
end
m
end
compare = lambda do |x, y|
x_versions = x.inject({}, &map)
y_versions = y.inject({}, &map)
# If the dependency is direct (not transitive), just compare its versions.
# Otherwise, add the result of comparison to score.
x_versions.inject(0) do |score, kv|
package = kv[0]
cmp = kv[1] <=> y_versions[package]
if user_deps.include?(package) && cmp != 0
return cmp
else
score += cmp unless cmp.nil?
end
score
end
end
permutations.sort(&compare)
end
|
ruby
|
def sort_permutations(permutations, user_deps)
# Cache for versions converted to Gem::Version instances
versions = {}
map = lambda do |m, p|
if p =~ Lyp::PACKAGE_RE
m[$1] = versions[p] ||= (Lyp.version($2 || '0.0') rescue nil)
end
m
end
compare = lambda do |x, y|
x_versions = x.inject({}, &map)
y_versions = y.inject({}, &map)
# If the dependency is direct (not transitive), just compare its versions.
# Otherwise, add the result of comparison to score.
x_versions.inject(0) do |score, kv|
package = kv[0]
cmp = kv[1] <=> y_versions[package]
if user_deps.include?(package) && cmp != 0
return cmp
else
score += cmp unless cmp.nil?
end
score
end
end
permutations.sort(&compare)
end
|
[
"def",
"sort_permutations",
"(",
"permutations",
",",
"user_deps",
")",
"# Cache for versions converted to Gem::Version instances",
"versions",
"=",
"{",
"}",
"map",
"=",
"lambda",
"do",
"|",
"m",
",",
"p",
"|",
"if",
"p",
"=~",
"Lyp",
"::",
"PACKAGE_RE",
"m",
"[",
"$1",
"]",
"=",
"versions",
"[",
"p",
"]",
"||=",
"(",
"Lyp",
".",
"version",
"(",
"$2",
"||",
"'0.0'",
")",
"rescue",
"nil",
")",
"end",
"m",
"end",
"compare",
"=",
"lambda",
"do",
"|",
"x",
",",
"y",
"|",
"x_versions",
"=",
"x",
".",
"inject",
"(",
"{",
"}",
",",
"map",
")",
"y_versions",
"=",
"y",
".",
"inject",
"(",
"{",
"}",
",",
"map",
")",
"# If the dependency is direct (not transitive), just compare its versions.",
"# Otherwise, add the result of comparison to score.",
"x_versions",
".",
"inject",
"(",
"0",
")",
"do",
"|",
"score",
",",
"kv",
"|",
"package",
"=",
"kv",
"[",
"0",
"]",
"cmp",
"=",
"kv",
"[",
"1",
"]",
"<=>",
"y_versions",
"[",
"package",
"]",
"if",
"user_deps",
".",
"include?",
"(",
"package",
")",
"&&",
"cmp",
"!=",
"0",
"return",
"cmp",
"else",
"score",
"+=",
"cmp",
"unless",
"cmp",
".",
"nil?",
"end",
"score",
"end",
"end",
"permutations",
".",
"sort",
"(",
"compare",
")",
"end"
] |
Sort permutations by version numbers
|
[
"Sort",
"permutations",
"by",
"version",
"numbers"
] |
cca29b702f65eb412cba50ba9d4e879e14930003
|
https://github.com/noteflakes/lyp/blob/cca29b702f65eb412cba50ba9d4e879e14930003/lib/lyp/resolver.rb#L375-L405
|
16,866
|
noteflakes/lyp
|
lib/lyp/resolver.rb
|
Lyp.DependencyResolver.find_matching_packages
|
def find_matching_packages(req)
return {} unless req =~ Lyp::PACKAGE_RE
req_package = $1
req_version = $2
req = nil
if @opts[:forced_package_paths] && @opts[:forced_package_paths][req_package]
req_version = 'forced'
end
req = Lyp.version_req(req_version || '>=0') rescue nil
available_packages.select do |package, leaf|
if (package =~ Lyp::PACKAGE_RE) && (req_package == $1)
version = Lyp.version($2 || '0') rescue nil
if version.nil? || req.nil?
req_version.nil? || (req_version == $2)
else
req =~ version
end
else
nil
end
end
end
|
ruby
|
def find_matching_packages(req)
return {} unless req =~ Lyp::PACKAGE_RE
req_package = $1
req_version = $2
req = nil
if @opts[:forced_package_paths] && @opts[:forced_package_paths][req_package]
req_version = 'forced'
end
req = Lyp.version_req(req_version || '>=0') rescue nil
available_packages.select do |package, leaf|
if (package =~ Lyp::PACKAGE_RE) && (req_package == $1)
version = Lyp.version($2 || '0') rescue nil
if version.nil? || req.nil?
req_version.nil? || (req_version == $2)
else
req =~ version
end
else
nil
end
end
end
|
[
"def",
"find_matching_packages",
"(",
"req",
")",
"return",
"{",
"}",
"unless",
"req",
"=~",
"Lyp",
"::",
"PACKAGE_RE",
"req_package",
"=",
"$1",
"req_version",
"=",
"$2",
"req",
"=",
"nil",
"if",
"@opts",
"[",
":forced_package_paths",
"]",
"&&",
"@opts",
"[",
":forced_package_paths",
"]",
"[",
"req_package",
"]",
"req_version",
"=",
"'forced'",
"end",
"req",
"=",
"Lyp",
".",
"version_req",
"(",
"req_version",
"||",
"'>=0'",
")",
"rescue",
"nil",
"available_packages",
".",
"select",
"do",
"|",
"package",
",",
"leaf",
"|",
"if",
"(",
"package",
"=~",
"Lyp",
"::",
"PACKAGE_RE",
")",
"&&",
"(",
"req_package",
"==",
"$1",
")",
"version",
"=",
"Lyp",
".",
"version",
"(",
"$2",
"||",
"'0'",
")",
"rescue",
"nil",
"if",
"version",
".",
"nil?",
"||",
"req",
".",
"nil?",
"req_version",
".",
"nil?",
"||",
"(",
"req_version",
"==",
"$2",
")",
"else",
"req",
"=~",
"version",
"end",
"else",
"nil",
"end",
"end",
"end"
] |
Find packages meeting the version requirement
|
[
"Find",
"packages",
"meeting",
"the",
"version",
"requirement"
] |
cca29b702f65eb412cba50ba9d4e879e14930003
|
https://github.com/noteflakes/lyp/blob/cca29b702f65eb412cba50ba9d4e879e14930003/lib/lyp/resolver.rb#L438-L462
|
16,867
|
noteflakes/lyp
|
lib/lyp/resolver.rb
|
Lyp.DependencyResolver.find_package_versions
|
def find_package_versions(ref, leaf, location)
return {} unless ref =~ Lyp::PACKAGE_RE
ref_package = $1
version_clause = $2
matches = find_matching_packages(ref)
# Raise if no match found and we're at top of the tree
if matches.empty? && (leaf == tree) && !opts[:ignore_missing]
msg = "Missing package dependency #{ref} in %sYou can install any missing packages by running:\n\n lyp resolve #{@user_file}"
error(msg, location)
end
matches.each do |p, package_leaf|
if package_leaf.path
queue_file_for_processing(package_leaf.path, package_leaf)
end
end
# Setup up dependency leaf
leaf.add_dependency(ref_package, DependencySpec.new(ref, matches, location))
end
|
ruby
|
def find_package_versions(ref, leaf, location)
return {} unless ref =~ Lyp::PACKAGE_RE
ref_package = $1
version_clause = $2
matches = find_matching_packages(ref)
# Raise if no match found and we're at top of the tree
if matches.empty? && (leaf == tree) && !opts[:ignore_missing]
msg = "Missing package dependency #{ref} in %sYou can install any missing packages by running:\n\n lyp resolve #{@user_file}"
error(msg, location)
end
matches.each do |p, package_leaf|
if package_leaf.path
queue_file_for_processing(package_leaf.path, package_leaf)
end
end
# Setup up dependency leaf
leaf.add_dependency(ref_package, DependencySpec.new(ref, matches, location))
end
|
[
"def",
"find_package_versions",
"(",
"ref",
",",
"leaf",
",",
"location",
")",
"return",
"{",
"}",
"unless",
"ref",
"=~",
"Lyp",
"::",
"PACKAGE_RE",
"ref_package",
"=",
"$1",
"version_clause",
"=",
"$2",
"matches",
"=",
"find_matching_packages",
"(",
"ref",
")",
"# Raise if no match found and we're at top of the tree",
"if",
"matches",
".",
"empty?",
"&&",
"(",
"leaf",
"==",
"tree",
")",
"&&",
"!",
"opts",
"[",
":ignore_missing",
"]",
"msg",
"=",
"\"Missing package dependency #{ref} in %sYou can install any missing packages by running:\\n\\n lyp resolve #{@user_file}\"",
"error",
"(",
"msg",
",",
"location",
")",
"end",
"matches",
".",
"each",
"do",
"|",
"p",
",",
"package_leaf",
"|",
"if",
"package_leaf",
".",
"path",
"queue_file_for_processing",
"(",
"package_leaf",
".",
"path",
",",
"package_leaf",
")",
"end",
"end",
"# Setup up dependency leaf",
"leaf",
".",
"add_dependency",
"(",
"ref_package",
",",
"DependencySpec",
".",
"new",
"(",
"ref",
",",
"matches",
",",
"location",
")",
")",
"end"
] |
Find available packaging matching the package specifier, and queue them for
processing any include files or transitive dependencies.
|
[
"Find",
"available",
"packaging",
"matching",
"the",
"package",
"specifier",
"and",
"queue",
"them",
"for",
"processing",
"any",
"include",
"files",
"or",
"transitive",
"dependencies",
"."
] |
cca29b702f65eb412cba50ba9d4e879e14930003
|
https://github.com/noteflakes/lyp/blob/cca29b702f65eb412cba50ba9d4e879e14930003/lib/lyp/resolver.rb#L466-L487
|
16,868
|
noteflakes/lyp
|
lib/lyp/resolver.rb
|
Lyp.DependencyResolver.squash_old_versions
|
def squash_old_versions
specifiers = map_specifiers_to_versions
compare_versions = lambda do |x, y|
v_x = x =~ Lyp::PACKAGE_RE && Lyp.version($2)
v_y = y =~ Lyp::PACKAGE_RE && Lyp.version($2)
x <=> y
end
specifiers.each do |package, clauses|
# Remove old versions only if the package is referenced using a single
# specifier clause
next unless clauses.size == 1
specs = clauses.values.first
specs.each do |s|
if s.versions.values.uniq.size == 1
versions = s.versions.keys.sort(&compare_versions)
latest = versions.last
s.versions.select! {|k, v| k == latest}
end
end
end
end
|
ruby
|
def squash_old_versions
specifiers = map_specifiers_to_versions
compare_versions = lambda do |x, y|
v_x = x =~ Lyp::PACKAGE_RE && Lyp.version($2)
v_y = y =~ Lyp::PACKAGE_RE && Lyp.version($2)
x <=> y
end
specifiers.each do |package, clauses|
# Remove old versions only if the package is referenced using a single
# specifier clause
next unless clauses.size == 1
specs = clauses.values.first
specs.each do |s|
if s.versions.values.uniq.size == 1
versions = s.versions.keys.sort(&compare_versions)
latest = versions.last
s.versions.select! {|k, v| k == latest}
end
end
end
end
|
[
"def",
"squash_old_versions",
"specifiers",
"=",
"map_specifiers_to_versions",
"compare_versions",
"=",
"lambda",
"do",
"|",
"x",
",",
"y",
"|",
"v_x",
"=",
"x",
"=~",
"Lyp",
"::",
"PACKAGE_RE",
"&&",
"Lyp",
".",
"version",
"(",
"$2",
")",
"v_y",
"=",
"y",
"=~",
"Lyp",
"::",
"PACKAGE_RE",
"&&",
"Lyp",
".",
"version",
"(",
"$2",
")",
"x",
"<=>",
"y",
"end",
"specifiers",
".",
"each",
"do",
"|",
"package",
",",
"clauses",
"|",
"# Remove old versions only if the package is referenced using a single",
"# specifier clause",
"next",
"unless",
"clauses",
".",
"size",
"==",
"1",
"specs",
"=",
"clauses",
".",
"values",
".",
"first",
"specs",
".",
"each",
"do",
"|",
"s",
"|",
"if",
"s",
".",
"versions",
".",
"values",
".",
"uniq",
".",
"size",
"==",
"1",
"versions",
"=",
"s",
".",
"versions",
".",
"keys",
".",
"sort",
"(",
"compare_versions",
")",
"latest",
"=",
"versions",
".",
"last",
"s",
".",
"versions",
".",
"select!",
"{",
"|",
"k",
",",
"v",
"|",
"k",
"==",
"latest",
"}",
"end",
"end",
"end",
"end"
] |
Remove redundant older versions of dependencies by collating package
versions by package specifiers, then removing older versions for any
package for which a single package specifier exists.
|
[
"Remove",
"redundant",
"older",
"versions",
"of",
"dependencies",
"by",
"collating",
"package",
"versions",
"by",
"package",
"specifiers",
"then",
"removing",
"older",
"versions",
"for",
"any",
"package",
"for",
"which",
"a",
"single",
"package",
"specifier",
"exists",
"."
] |
cca29b702f65eb412cba50ba9d4e879e14930003
|
https://github.com/noteflakes/lyp/blob/cca29b702f65eb412cba50ba9d4e879e14930003/lib/lyp/resolver.rb#L492-L515
|
16,869
|
noteflakes/lyp
|
lib/lyp/resolver.rb
|
Lyp.DependencyResolver.map_specifiers_to_versions
|
def map_specifiers_to_versions
specifiers = {}
processed = {}
l = lambda do |t|
return if processed[t.object_id]
processed[t.object_id] = true
t.dependencies.each do |package, spec|
specifiers[package] ||= {}
specifiers[package][spec.clause] ||= []
specifiers[package][spec.clause] << spec
spec.versions.each_value {|v| l[v]}
end
end
l[@tree]
specifiers
end
|
ruby
|
def map_specifiers_to_versions
specifiers = {}
processed = {}
l = lambda do |t|
return if processed[t.object_id]
processed[t.object_id] = true
t.dependencies.each do |package, spec|
specifiers[package] ||= {}
specifiers[package][spec.clause] ||= []
specifiers[package][spec.clause] << spec
spec.versions.each_value {|v| l[v]}
end
end
l[@tree]
specifiers
end
|
[
"def",
"map_specifiers_to_versions",
"specifiers",
"=",
"{",
"}",
"processed",
"=",
"{",
"}",
"l",
"=",
"lambda",
"do",
"|",
"t",
"|",
"return",
"if",
"processed",
"[",
"t",
".",
"object_id",
"]",
"processed",
"[",
"t",
".",
"object_id",
"]",
"=",
"true",
"t",
".",
"dependencies",
".",
"each",
"do",
"|",
"package",
",",
"spec",
"|",
"specifiers",
"[",
"package",
"]",
"||=",
"{",
"}",
"specifiers",
"[",
"package",
"]",
"[",
"spec",
".",
"clause",
"]",
"||=",
"[",
"]",
"specifiers",
"[",
"package",
"]",
"[",
"spec",
".",
"clause",
"]",
"<<",
"spec",
"spec",
".",
"versions",
".",
"each_value",
"{",
"|",
"v",
"|",
"l",
"[",
"v",
"]",
"}",
"end",
"end",
"l",
"[",
"@tree",
"]",
"specifiers",
"end"
] |
Return a hash mapping packages to package specifiers to spec objects, to
be used to eliminate older versions from the dependency tree
|
[
"Return",
"a",
"hash",
"mapping",
"packages",
"to",
"package",
"specifiers",
"to",
"spec",
"objects",
"to",
"be",
"used",
"to",
"eliminate",
"older",
"versions",
"from",
"the",
"dependency",
"tree"
] |
cca29b702f65eb412cba50ba9d4e879e14930003
|
https://github.com/noteflakes/lyp/blob/cca29b702f65eb412cba50ba9d4e879e14930003/lib/lyp/resolver.rb#L519-L536
|
16,870
|
noteflakes/lyp
|
lib/lyp/resolver.rb
|
Lyp.DependencyResolver.remove_unfulfilled_dependencies
|
def remove_unfulfilled_dependencies(leaf, raise_on_missing = true, processed = {})
tree.dependencies.each do |package, dependency|
dependency.versions.select! do |version, leaf|
if processed[version]
true
else
processed[version] = true
# Remove unfulfilled transitive dependencies
remove_unfulfilled_dependencies(leaf, false, processed)
valid = true
leaf.dependencies.each do |k, v|
valid = false if v.versions.empty?
end
valid
end
end
if dependency.versions.empty? && raise_on_missing
error("No valid version found for package #{package}")
end
end
end
|
ruby
|
def remove_unfulfilled_dependencies(leaf, raise_on_missing = true, processed = {})
tree.dependencies.each do |package, dependency|
dependency.versions.select! do |version, leaf|
if processed[version]
true
else
processed[version] = true
# Remove unfulfilled transitive dependencies
remove_unfulfilled_dependencies(leaf, false, processed)
valid = true
leaf.dependencies.each do |k, v|
valid = false if v.versions.empty?
end
valid
end
end
if dependency.versions.empty? && raise_on_missing
error("No valid version found for package #{package}")
end
end
end
|
[
"def",
"remove_unfulfilled_dependencies",
"(",
"leaf",
",",
"raise_on_missing",
"=",
"true",
",",
"processed",
"=",
"{",
"}",
")",
"tree",
".",
"dependencies",
".",
"each",
"do",
"|",
"package",
",",
"dependency",
"|",
"dependency",
".",
"versions",
".",
"select!",
"do",
"|",
"version",
",",
"leaf",
"|",
"if",
"processed",
"[",
"version",
"]",
"true",
"else",
"processed",
"[",
"version",
"]",
"=",
"true",
"# Remove unfulfilled transitive dependencies",
"remove_unfulfilled_dependencies",
"(",
"leaf",
",",
"false",
",",
"processed",
")",
"valid",
"=",
"true",
"leaf",
".",
"dependencies",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"valid",
"=",
"false",
"if",
"v",
".",
"versions",
".",
"empty?",
"end",
"valid",
"end",
"end",
"if",
"dependency",
".",
"versions",
".",
"empty?",
"&&",
"raise_on_missing",
"error",
"(",
"\"No valid version found for package #{package}\"",
")",
"end",
"end",
"end"
] |
Recursively remove any dependency for which no version is locally
available. If no version is found for any of the dependencies specified
by the user, an error is raised.
The processed hash is used for keeping track of dependencies that were
already processed, and thus deal with circular dependencies.
|
[
"Recursively",
"remove",
"any",
"dependency",
"for",
"which",
"no",
"version",
"is",
"locally",
"available",
".",
"If",
"no",
"version",
"is",
"found",
"for",
"any",
"of",
"the",
"dependencies",
"specified",
"by",
"the",
"user",
"an",
"error",
"is",
"raised",
"."
] |
cca29b702f65eb412cba50ba9d4e879e14930003
|
https://github.com/noteflakes/lyp/blob/cca29b702f65eb412cba50ba9d4e879e14930003/lib/lyp/resolver.rb#L544-L565
|
16,871
|
airbrake/airbrake-ruby
|
lib/airbrake-ruby/filter_chain.rb
|
Airbrake.FilterChain.add_filter
|
def add_filter(filter)
@filters = (@filters << filter).sort_by do |f|
f.respond_to?(:weight) ? f.weight : DEFAULT_WEIGHT
end.reverse!
end
|
ruby
|
def add_filter(filter)
@filters = (@filters << filter).sort_by do |f|
f.respond_to?(:weight) ? f.weight : DEFAULT_WEIGHT
end.reverse!
end
|
[
"def",
"add_filter",
"(",
"filter",
")",
"@filters",
"=",
"(",
"@filters",
"<<",
"filter",
")",
".",
"sort_by",
"do",
"|",
"f",
"|",
"f",
".",
"respond_to?",
"(",
":weight",
")",
"?",
"f",
".",
"weight",
":",
"DEFAULT_WEIGHT",
"end",
".",
"reverse!",
"end"
] |
Adds a filter to the filter chain. Sorts filters by weight.
@param [#call] filter The filter object (proc, class, module, etc)
@return [void]
|
[
"Adds",
"a",
"filter",
"to",
"the",
"filter",
"chain",
".",
"Sorts",
"filters",
"by",
"weight",
"."
] |
bb560edf03df57b559e1dee1d2e9ec6480a686b8
|
https://github.com/airbrake/airbrake-ruby/blob/bb560edf03df57b559e1dee1d2e9ec6480a686b8/lib/airbrake-ruby/filter_chain.rb#L48-L52
|
16,872
|
airbrake/airbrake-ruby
|
lib/airbrake-ruby/filter_chain.rb
|
Airbrake.FilterChain.delete_filter
|
def delete_filter(filter_class)
index = @filters.index { |f| f.class.name == filter_class.name }
@filters.delete_at(index) if index
end
|
ruby
|
def delete_filter(filter_class)
index = @filters.index { |f| f.class.name == filter_class.name }
@filters.delete_at(index) if index
end
|
[
"def",
"delete_filter",
"(",
"filter_class",
")",
"index",
"=",
"@filters",
".",
"index",
"{",
"|",
"f",
"|",
"f",
".",
"class",
".",
"name",
"==",
"filter_class",
".",
"name",
"}",
"@filters",
".",
"delete_at",
"(",
"index",
")",
"if",
"index",
"end"
] |
Deletes a filter from the the filter chain.
@param [Class] filter_class The class of the filter you want to delete
@return [void]
@since v3.1.0
|
[
"Deletes",
"a",
"filter",
"from",
"the",
"the",
"filter",
"chain",
"."
] |
bb560edf03df57b559e1dee1d2e9ec6480a686b8
|
https://github.com/airbrake/airbrake-ruby/blob/bb560edf03df57b559e1dee1d2e9ec6480a686b8/lib/airbrake-ruby/filter_chain.rb#L59-L62
|
16,873
|
airbrake/airbrake-ruby
|
lib/airbrake-ruby/truncator.rb
|
Airbrake.Truncator.replace_invalid_characters
|
def replace_invalid_characters(str)
encoding = str.encoding
utf8_string = (encoding == Encoding::UTF_8 || encoding == Encoding::ASCII)
return str if utf8_string && str.valid_encoding?
temp_str = str.dup
temp_str.encode!(TEMP_ENCODING, ENCODING_OPTIONS) if utf8_string
temp_str.encode!('utf-8', ENCODING_OPTIONS)
end
|
ruby
|
def replace_invalid_characters(str)
encoding = str.encoding
utf8_string = (encoding == Encoding::UTF_8 || encoding == Encoding::ASCII)
return str if utf8_string && str.valid_encoding?
temp_str = str.dup
temp_str.encode!(TEMP_ENCODING, ENCODING_OPTIONS) if utf8_string
temp_str.encode!('utf-8', ENCODING_OPTIONS)
end
|
[
"def",
"replace_invalid_characters",
"(",
"str",
")",
"encoding",
"=",
"str",
".",
"encoding",
"utf8_string",
"=",
"(",
"encoding",
"==",
"Encoding",
"::",
"UTF_8",
"||",
"encoding",
"==",
"Encoding",
"::",
"ASCII",
")",
"return",
"str",
"if",
"utf8_string",
"&&",
"str",
".",
"valid_encoding?",
"temp_str",
"=",
"str",
".",
"dup",
"temp_str",
".",
"encode!",
"(",
"TEMP_ENCODING",
",",
"ENCODING_OPTIONS",
")",
"if",
"utf8_string",
"temp_str",
".",
"encode!",
"(",
"'utf-8'",
",",
"ENCODING_OPTIONS",
")",
"end"
] |
Replaces invalid characters in a string with arbitrary encoding.
@param [String] str The string to replace characters
@return [String] a UTF-8 encoded string
@see https://github.com/flori/json/commit/3e158410e81f94dbbc3da6b7b35f4f64983aa4e3
|
[
"Replaces",
"invalid",
"characters",
"in",
"a",
"string",
"with",
"arbitrary",
"encoding",
"."
] |
bb560edf03df57b559e1dee1d2e9ec6480a686b8
|
https://github.com/airbrake/airbrake-ruby/blob/bb560edf03df57b559e1dee1d2e9ec6480a686b8/lib/airbrake-ruby/truncator.rb#L105-L113
|
16,874
|
airbrake/airbrake-ruby
|
lib/airbrake-ruby/async_sender.rb
|
Airbrake.AsyncSender.send
|
def send(notice, promise)
return will_not_deliver(notice) if @unsent.size >= @unsent.max
@unsent << [notice, promise]
promise
end
|
ruby
|
def send(notice, promise)
return will_not_deliver(notice) if @unsent.size >= @unsent.max
@unsent << [notice, promise]
promise
end
|
[
"def",
"send",
"(",
"notice",
",",
"promise",
")",
"return",
"will_not_deliver",
"(",
"notice",
")",
"if",
"@unsent",
".",
"size",
">=",
"@unsent",
".",
"max",
"@unsent",
"<<",
"[",
"notice",
",",
"promise",
"]",
"promise",
"end"
] |
Asynchronously sends a notice to Airbrake.
@param [Airbrake::Notice] notice A notice that was generated by the
library
@return [Airbrake::Promise]
|
[
"Asynchronously",
"sends",
"a",
"notice",
"to",
"Airbrake",
"."
] |
bb560edf03df57b559e1dee1d2e9ec6480a686b8
|
https://github.com/airbrake/airbrake-ruby/blob/bb560edf03df57b559e1dee1d2e9ec6480a686b8/lib/airbrake-ruby/async_sender.rb#L38-L43
|
16,875
|
airbrake/airbrake-ruby
|
lib/airbrake-ruby/notice.rb
|
Airbrake.Notice.[]=
|
def []=(key, value)
raise_if_ignored
unless WRITABLE_KEYS.include?(key)
raise Airbrake::Error,
":#{key} is not recognized among #{WRITABLE_KEYS}"
end
unless value.respond_to?(:to_hash)
raise Airbrake::Error, "Got #{value.class} value, wanted a Hash"
end
@payload[key] = value.to_hash
end
|
ruby
|
def []=(key, value)
raise_if_ignored
unless WRITABLE_KEYS.include?(key)
raise Airbrake::Error,
":#{key} is not recognized among #{WRITABLE_KEYS}"
end
unless value.respond_to?(:to_hash)
raise Airbrake::Error, "Got #{value.class} value, wanted a Hash"
end
@payload[key] = value.to_hash
end
|
[
"def",
"[]=",
"(",
"key",
",",
"value",
")",
"raise_if_ignored",
"unless",
"WRITABLE_KEYS",
".",
"include?",
"(",
"key",
")",
"raise",
"Airbrake",
"::",
"Error",
",",
"\":#{key} is not recognized among #{WRITABLE_KEYS}\"",
"end",
"unless",
"value",
".",
"respond_to?",
"(",
":to_hash",
")",
"raise",
"Airbrake",
"::",
"Error",
",",
"\"Got #{value.class} value, wanted a Hash\"",
"end",
"@payload",
"[",
"key",
"]",
"=",
"value",
".",
"to_hash",
"end"
] |
Writes a value to the payload hash. Restricts unrecognized writes.
@example
notice[:params][:my_param] = 'foobar'
@return [void]
@raise [Airbrake::Error] if the notice is ignored
@raise [Airbrake::Error] if the +key+ is not recognized
@raise [Airbrake::Error] if the root value is not a Hash
|
[
"Writes",
"a",
"value",
"to",
"the",
"payload",
"hash",
".",
"Restricts",
"unrecognized",
"writes",
"."
] |
bb560edf03df57b559e1dee1d2e9ec6480a686b8
|
https://github.com/airbrake/airbrake-ruby/blob/bb560edf03df57b559e1dee1d2e9ec6480a686b8/lib/airbrake-ruby/notice.rb#L114-L127
|
16,876
|
ashfurrow/danger-ruby-swiftlint
|
lib/danger_plugin.rb
|
Danger.DangerSwiftlint.run_swiftlint
|
def run_swiftlint(files, lint_all_files, options, additional_swiftlint_args)
if lint_all_files
result = swiftlint.lint(options, additional_swiftlint_args)
if result == ''
{}
else
JSON.parse(result).flatten
end
else
files
.map { |file| options.merge(path: file) }
.map { |full_options| swiftlint.lint(full_options, additional_swiftlint_args) }
.reject { |s| s == '' }
.map { |s| JSON.parse(s).flatten }
.flatten
end
end
|
ruby
|
def run_swiftlint(files, lint_all_files, options, additional_swiftlint_args)
if lint_all_files
result = swiftlint.lint(options, additional_swiftlint_args)
if result == ''
{}
else
JSON.parse(result).flatten
end
else
files
.map { |file| options.merge(path: file) }
.map { |full_options| swiftlint.lint(full_options, additional_swiftlint_args) }
.reject { |s| s == '' }
.map { |s| JSON.parse(s).flatten }
.flatten
end
end
|
[
"def",
"run_swiftlint",
"(",
"files",
",",
"lint_all_files",
",",
"options",
",",
"additional_swiftlint_args",
")",
"if",
"lint_all_files",
"result",
"=",
"swiftlint",
".",
"lint",
"(",
"options",
",",
"additional_swiftlint_args",
")",
"if",
"result",
"==",
"''",
"{",
"}",
"else",
"JSON",
".",
"parse",
"(",
"result",
")",
".",
"flatten",
"end",
"else",
"files",
".",
"map",
"{",
"|",
"file",
"|",
"options",
".",
"merge",
"(",
"path",
":",
"file",
")",
"}",
".",
"map",
"{",
"|",
"full_options",
"|",
"swiftlint",
".",
"lint",
"(",
"full_options",
",",
"additional_swiftlint_args",
")",
"}",
".",
"reject",
"{",
"|",
"s",
"|",
"s",
"==",
"''",
"}",
".",
"map",
"{",
"|",
"s",
"|",
"JSON",
".",
"parse",
"(",
"s",
")",
".",
"flatten",
"}",
".",
"flatten",
"end",
"end"
] |
Run swiftlint on each file and aggregate collect the issues
@return [Array] swiftlint issues
|
[
"Run",
"swiftlint",
"on",
"each",
"file",
"and",
"aggregate",
"collect",
"the",
"issues"
] |
a6ff2fbf492433c865ffc66feffede1d2d1e2f4d
|
https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L153-L169
|
16,877
|
ashfurrow/danger-ruby-swiftlint
|
lib/danger_plugin.rb
|
Danger.DangerSwiftlint.find_swift_files
|
def find_swift_files(dir_selected, files = nil, excluded_paths = [], included_paths = [])
# Needs to be escaped before comparsion with escaped file paths
dir_selected = Shellwords.escape(dir_selected)
# Assign files to lint
files = if files.nil?
(git.modified_files - git.deleted_files) + git.added_files
else
Dir.glob(files)
end
# Filter files to lint
files.
# Ensure only swift files are selected
select { |file| file.end_with?('.swift') }.
# Make sure we don't fail when paths have spaces
map { |file| Shellwords.escape(File.expand_path(file)) }.
# Remove dups
uniq.
# Ensure only files in the selected directory
select { |file| file.start_with?(dir_selected) }.
# Reject files excluded on configuration
reject { |file| file_exists?(excluded_paths, file) }.
# Accept files included on configuration
select do |file|
next true if included_paths.empty?
file_exists?(included_paths, file)
end
end
|
ruby
|
def find_swift_files(dir_selected, files = nil, excluded_paths = [], included_paths = [])
# Needs to be escaped before comparsion with escaped file paths
dir_selected = Shellwords.escape(dir_selected)
# Assign files to lint
files = if files.nil?
(git.modified_files - git.deleted_files) + git.added_files
else
Dir.glob(files)
end
# Filter files to lint
files.
# Ensure only swift files are selected
select { |file| file.end_with?('.swift') }.
# Make sure we don't fail when paths have spaces
map { |file| Shellwords.escape(File.expand_path(file)) }.
# Remove dups
uniq.
# Ensure only files in the selected directory
select { |file| file.start_with?(dir_selected) }.
# Reject files excluded on configuration
reject { |file| file_exists?(excluded_paths, file) }.
# Accept files included on configuration
select do |file|
next true if included_paths.empty?
file_exists?(included_paths, file)
end
end
|
[
"def",
"find_swift_files",
"(",
"dir_selected",
",",
"files",
"=",
"nil",
",",
"excluded_paths",
"=",
"[",
"]",
",",
"included_paths",
"=",
"[",
"]",
")",
"# Needs to be escaped before comparsion with escaped file paths",
"dir_selected",
"=",
"Shellwords",
".",
"escape",
"(",
"dir_selected",
")",
"# Assign files to lint",
"files",
"=",
"if",
"files",
".",
"nil?",
"(",
"git",
".",
"modified_files",
"-",
"git",
".",
"deleted_files",
")",
"+",
"git",
".",
"added_files",
"else",
"Dir",
".",
"glob",
"(",
"files",
")",
"end",
"# Filter files to lint",
"files",
".",
"# Ensure only swift files are selected",
"select",
"{",
"|",
"file",
"|",
"file",
".",
"end_with?",
"(",
"'.swift'",
")",
"}",
".",
"# Make sure we don't fail when paths have spaces",
"map",
"{",
"|",
"file",
"|",
"Shellwords",
".",
"escape",
"(",
"File",
".",
"expand_path",
"(",
"file",
")",
")",
"}",
".",
"# Remove dups",
"uniq",
".",
"# Ensure only files in the selected directory",
"select",
"{",
"|",
"file",
"|",
"file",
".",
"start_with?",
"(",
"dir_selected",
")",
"}",
".",
"# Reject files excluded on configuration",
"reject",
"{",
"|",
"file",
"|",
"file_exists?",
"(",
"excluded_paths",
",",
"file",
")",
"}",
".",
"# Accept files included on configuration",
"select",
"do",
"|",
"file",
"|",
"next",
"true",
"if",
"included_paths",
".",
"empty?",
"file_exists?",
"(",
"included_paths",
",",
"file",
")",
"end",
"end"
] |
Find swift files from the files glob
If files are not provided it will use git modifield and added files
@return [Array] swift files
|
[
"Find",
"swift",
"files",
"from",
"the",
"files",
"glob",
"If",
"files",
"are",
"not",
"provided",
"it",
"will",
"use",
"git",
"modifield",
"and",
"added",
"files"
] |
a6ff2fbf492433c865ffc66feffede1d2d1e2f4d
|
https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L175-L202
|
16,878
|
ashfurrow/danger-ruby-swiftlint
|
lib/danger_plugin.rb
|
Danger.DangerSwiftlint.load_config
|
def load_config(filepath)
return {} if filepath.nil? || !File.exist?(filepath)
config_file = File.open(filepath).read
# Replace environment variables
config_file = parse_environment_variables(config_file)
YAML.safe_load(config_file)
end
|
ruby
|
def load_config(filepath)
return {} if filepath.nil? || !File.exist?(filepath)
config_file = File.open(filepath).read
# Replace environment variables
config_file = parse_environment_variables(config_file)
YAML.safe_load(config_file)
end
|
[
"def",
"load_config",
"(",
"filepath",
")",
"return",
"{",
"}",
"if",
"filepath",
".",
"nil?",
"||",
"!",
"File",
".",
"exist?",
"(",
"filepath",
")",
"config_file",
"=",
"File",
".",
"open",
"(",
"filepath",
")",
".",
"read",
"# Replace environment variables",
"config_file",
"=",
"parse_environment_variables",
"(",
"config_file",
")",
"YAML",
".",
"safe_load",
"(",
"config_file",
")",
"end"
] |
Get the configuration file
|
[
"Get",
"the",
"configuration",
"file"
] |
a6ff2fbf492433c865ffc66feffede1d2d1e2f4d
|
https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L205-L214
|
16,879
|
ashfurrow/danger-ruby-swiftlint
|
lib/danger_plugin.rb
|
Danger.DangerSwiftlint.parse_environment_variables
|
def parse_environment_variables(file_contents)
# Matches the file contents for environment variables defined like ${VAR_NAME}.
# Replaces them with the environment variable value if it exists.
file_contents.gsub(/\$\{([^{}]+)\}/) do |env_var|
return env_var if ENV[Regexp.last_match[1]].nil?
ENV[Regexp.last_match[1]]
end
end
|
ruby
|
def parse_environment_variables(file_contents)
# Matches the file contents for environment variables defined like ${VAR_NAME}.
# Replaces them with the environment variable value if it exists.
file_contents.gsub(/\$\{([^{}]+)\}/) do |env_var|
return env_var if ENV[Regexp.last_match[1]].nil?
ENV[Regexp.last_match[1]]
end
end
|
[
"def",
"parse_environment_variables",
"(",
"file_contents",
")",
"# Matches the file contents for environment variables defined like ${VAR_NAME}.",
"# Replaces them with the environment variable value if it exists.",
"file_contents",
".",
"gsub",
"(",
"/",
"\\$",
"\\{",
"\\}",
"/",
")",
"do",
"|",
"env_var",
"|",
"return",
"env_var",
"if",
"ENV",
"[",
"Regexp",
".",
"last_match",
"[",
"1",
"]",
"]",
".",
"nil?",
"ENV",
"[",
"Regexp",
".",
"last_match",
"[",
"1",
"]",
"]",
"end",
"end"
] |
Find all requested environment variables in the given string and replace them with the correct values.
|
[
"Find",
"all",
"requested",
"environment",
"variables",
"in",
"the",
"given",
"string",
"and",
"replace",
"them",
"with",
"the",
"correct",
"values",
"."
] |
a6ff2fbf492433c865ffc66feffede1d2d1e2f4d
|
https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L217-L224
|
16,880
|
ashfurrow/danger-ruby-swiftlint
|
lib/danger_plugin.rb
|
Danger.DangerSwiftlint.file_exists?
|
def file_exists?(paths, file)
paths.any? do |path|
Find.find(path)
.map { |path_file| Shellwords.escape(path_file) }
.include?(file)
end
end
|
ruby
|
def file_exists?(paths, file)
paths.any? do |path|
Find.find(path)
.map { |path_file| Shellwords.escape(path_file) }
.include?(file)
end
end
|
[
"def",
"file_exists?",
"(",
"paths",
",",
"file",
")",
"paths",
".",
"any?",
"do",
"|",
"path",
"|",
"Find",
".",
"find",
"(",
"path",
")",
".",
"map",
"{",
"|",
"path_file",
"|",
"Shellwords",
".",
"escape",
"(",
"path_file",
")",
"}",
".",
"include?",
"(",
"file",
")",
"end",
"end"
] |
Return whether the file exists within a specified collection of paths
@return [Bool] file exists within specified collection of paths
|
[
"Return",
"whether",
"the",
"file",
"exists",
"within",
"a",
"specified",
"collection",
"of",
"paths"
] |
a6ff2fbf492433c865ffc66feffede1d2d1e2f4d
|
https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L229-L235
|
16,881
|
ashfurrow/danger-ruby-swiftlint
|
lib/danger_plugin.rb
|
Danger.DangerSwiftlint.format_paths
|
def format_paths(paths, filepath)
# Extract included paths
paths
.map { |path| File.join(File.dirname(filepath), path) }
.map { |path| File.expand_path(path) }
.select { |path| File.exist?(path) || Dir.exist?(path) }
end
|
ruby
|
def format_paths(paths, filepath)
# Extract included paths
paths
.map { |path| File.join(File.dirname(filepath), path) }
.map { |path| File.expand_path(path) }
.select { |path| File.exist?(path) || Dir.exist?(path) }
end
|
[
"def",
"format_paths",
"(",
"paths",
",",
"filepath",
")",
"# Extract included paths",
"paths",
".",
"map",
"{",
"|",
"path",
"|",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"filepath",
")",
",",
"path",
")",
"}",
".",
"map",
"{",
"|",
"path",
"|",
"File",
".",
"expand_path",
"(",
"path",
")",
"}",
".",
"select",
"{",
"|",
"path",
"|",
"File",
".",
"exist?",
"(",
"path",
")",
"||",
"Dir",
".",
"exist?",
"(",
"path",
")",
"}",
"end"
] |
Parses the configuration file and return the specified files in path
@return [Array] list of files specified in path
|
[
"Parses",
"the",
"configuration",
"file",
"and",
"return",
"the",
"specified",
"files",
"in",
"path"
] |
a6ff2fbf492433c865ffc66feffede1d2d1e2f4d
|
https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L240-L246
|
16,882
|
ashfurrow/danger-ruby-swiftlint
|
lib/danger_plugin.rb
|
Danger.DangerSwiftlint.markdown_issues
|
def markdown_issues(results, heading)
message = "#### #{heading}\n\n".dup
message << "File | Line | Reason |\n"
message << "| --- | ----- | ----- |\n"
results.each do |r|
filename = r['file'].split('/').last
line = r['line']
reason = r['reason']
rule = r['rule_id']
# Other available properties can be found int SwiftLint/…/JSONReporter.swift
message << "#{filename} | #{line} | #{reason} (#{rule})\n"
end
message
end
|
ruby
|
def markdown_issues(results, heading)
message = "#### #{heading}\n\n".dup
message << "File | Line | Reason |\n"
message << "| --- | ----- | ----- |\n"
results.each do |r|
filename = r['file'].split('/').last
line = r['line']
reason = r['reason']
rule = r['rule_id']
# Other available properties can be found int SwiftLint/…/JSONReporter.swift
message << "#{filename} | #{line} | #{reason} (#{rule})\n"
end
message
end
|
[
"def",
"markdown_issues",
"(",
"results",
",",
"heading",
")",
"message",
"=",
"\"#### #{heading}\\n\\n\"",
".",
"dup",
"message",
"<<",
"\"File | Line | Reason |\\n\"",
"message",
"<<",
"\"| --- | ----- | ----- |\\n\"",
"results",
".",
"each",
"do",
"|",
"r",
"|",
"filename",
"=",
"r",
"[",
"'file'",
"]",
".",
"split",
"(",
"'/'",
")",
".",
"last",
"line",
"=",
"r",
"[",
"'line'",
"]",
"reason",
"=",
"r",
"[",
"'reason'",
"]",
"rule",
"=",
"r",
"[",
"'rule_id'",
"]",
"# Other available properties can be found int SwiftLint/…/JSONReporter.swift",
"message",
"<<",
"\"#{filename} | #{line} | #{reason} (#{rule})\\n\"",
"end",
"message",
"end"
] |
Create a markdown table from swiftlint issues
@return [String]
|
[
"Create",
"a",
"markdown",
"table",
"from",
"swiftlint",
"issues"
] |
a6ff2fbf492433c865ffc66feffede1d2d1e2f4d
|
https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L251-L267
|
16,883
|
pusher/pusher-http-ruby
|
lib/pusher/webhook.rb
|
Pusher.WebHook.check_signature
|
def check_signature(secret)
digest = OpenSSL::Digest::SHA256.new
expected = OpenSSL::HMAC.hexdigest(digest, secret, @body)
if @signature == expected
return true
else
Pusher.logger.warn "Received WebHook with invalid signature: got #{@signature}, expected #{expected}"
return false
end
end
|
ruby
|
def check_signature(secret)
digest = OpenSSL::Digest::SHA256.new
expected = OpenSSL::HMAC.hexdigest(digest, secret, @body)
if @signature == expected
return true
else
Pusher.logger.warn "Received WebHook with invalid signature: got #{@signature}, expected #{expected}"
return false
end
end
|
[
"def",
"check_signature",
"(",
"secret",
")",
"digest",
"=",
"OpenSSL",
"::",
"Digest",
"::",
"SHA256",
".",
"new",
"expected",
"=",
"OpenSSL",
"::",
"HMAC",
".",
"hexdigest",
"(",
"digest",
",",
"secret",
",",
"@body",
")",
"if",
"@signature",
"==",
"expected",
"return",
"true",
"else",
"Pusher",
".",
"logger",
".",
"warn",
"\"Received WebHook with invalid signature: got #{@signature}, expected #{expected}\"",
"return",
"false",
"end",
"end"
] |
Checks signature against secret and returns boolean
|
[
"Checks",
"signature",
"against",
"secret",
"and",
"returns",
"boolean"
] |
cd666ca74b39dacfae6ca0235c35fcf80eba1e64
|
https://github.com/pusher/pusher-http-ruby/blob/cd666ca74b39dacfae6ca0235c35fcf80eba1e64/lib/pusher/webhook.rb#L99-L108
|
16,884
|
pusher/pusher-http-ruby
|
lib/pusher/client.rb
|
Pusher.Client.url=
|
def url=(url)
uri = URI.parse(url)
@scheme = uri.scheme
@app_id = uri.path.split('/').last
@key = uri.user
@secret = uri.password
@host = uri.host
@port = uri.port
end
|
ruby
|
def url=(url)
uri = URI.parse(url)
@scheme = uri.scheme
@app_id = uri.path.split('/').last
@key = uri.user
@secret = uri.password
@host = uri.host
@port = uri.port
end
|
[
"def",
"url",
"=",
"(",
"url",
")",
"uri",
"=",
"URI",
".",
"parse",
"(",
"url",
")",
"@scheme",
"=",
"uri",
".",
"scheme",
"@app_id",
"=",
"uri",
".",
"path",
".",
"split",
"(",
"'/'",
")",
".",
"last",
"@key",
"=",
"uri",
".",
"user",
"@secret",
"=",
"uri",
".",
"password",
"@host",
"=",
"uri",
".",
"host",
"@port",
"=",
"uri",
".",
"port",
"end"
] |
Configure Pusher connection by providing a url rather than specifying
scheme, key, secret, and app_id separately.
@example
Pusher.url = http://KEY:SECRET@api.pusherapp.com/apps/APP_ID
|
[
"Configure",
"Pusher",
"connection",
"by",
"providing",
"a",
"url",
"rather",
"than",
"specifying",
"scheme",
"key",
"secret",
"and",
"app_id",
"separately",
"."
] |
cd666ca74b39dacfae6ca0235c35fcf80eba1e64
|
https://github.com/pusher/pusher-http-ruby/blob/cd666ca74b39dacfae6ca0235c35fcf80eba1e64/lib/pusher/client.rb#L92-L100
|
16,885
|
pusher/pusher-http-ruby
|
lib/pusher/client.rb
|
Pusher.Client.trigger
|
def trigger(channels, event_name, data, params = {})
post('/events', trigger_params(channels, event_name, data, params))
end
|
ruby
|
def trigger(channels, event_name, data, params = {})
post('/events', trigger_params(channels, event_name, data, params))
end
|
[
"def",
"trigger",
"(",
"channels",
",",
"event_name",
",",
"data",
",",
"params",
"=",
"{",
"}",
")",
"post",
"(",
"'/events'",
",",
"trigger_params",
"(",
"channels",
",",
"event_name",
",",
"data",
",",
"params",
")",
")",
"end"
] |
Trigger an event on one or more channels
POST /apps/[app_id]/events
@param channels [String or Array] 1-10 channel names
@param event_name [String]
@param data [Object] Event data to be triggered in javascript.
Objects other than strings will be converted to JSON
@param params [Hash] Additional parameters to send to api, e.g socket_id
@return [Hash] See Pusher API docs
@raise [Pusher::Error] Unsuccessful response - see the error message
@raise [Pusher::HTTPError] Error raised inside http client. The original error is wrapped in error.original_error
|
[
"Trigger",
"an",
"event",
"on",
"one",
"or",
"more",
"channels"
] |
cd666ca74b39dacfae6ca0235c35fcf80eba1e64
|
https://github.com/pusher/pusher-http-ruby/blob/cd666ca74b39dacfae6ca0235c35fcf80eba1e64/lib/pusher/client.rb#L287-L289
|
16,886
|
pusher/pusher-http-ruby
|
lib/pusher/channel.rb
|
Pusher.Channel.trigger
|
def trigger(event_name, data, socket_id = nil)
trigger!(event_name, data, socket_id)
rescue Pusher::Error => e
Pusher.logger.error("#{e.message} (#{e.class})")
Pusher.logger.debug(e.backtrace.join("\n"))
end
|
ruby
|
def trigger(event_name, data, socket_id = nil)
trigger!(event_name, data, socket_id)
rescue Pusher::Error => e
Pusher.logger.error("#{e.message} (#{e.class})")
Pusher.logger.debug(e.backtrace.join("\n"))
end
|
[
"def",
"trigger",
"(",
"event_name",
",",
"data",
",",
"socket_id",
"=",
"nil",
")",
"trigger!",
"(",
"event_name",
",",
"data",
",",
"socket_id",
")",
"rescue",
"Pusher",
"::",
"Error",
"=>",
"e",
"Pusher",
".",
"logger",
".",
"error",
"(",
"\"#{e.message} (#{e.class})\"",
")",
"Pusher",
".",
"logger",
".",
"debug",
"(",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"end"
] |
Trigger event, catching and logging any errors.
[Deprecated] This method will be removed in a future gem version. Please
switch to Pusher.trigger or Pusher::Client#trigger instead
@note CAUTION! No exceptions will be raised on failure
@param (see #trigger!)
|
[
"Trigger",
"event",
"catching",
"and",
"logging",
"any",
"errors",
"."
] |
cd666ca74b39dacfae6ca0235c35fcf80eba1e64
|
https://github.com/pusher/pusher-http-ruby/blob/cd666ca74b39dacfae6ca0235c35fcf80eba1e64/lib/pusher/channel.rb#L80-L85
|
16,887
|
pusher/pusher-http-ruby
|
lib/pusher/channel.rb
|
Pusher.Channel.authentication_string
|
def authentication_string(socket_id, custom_string = nil)
validate_socket_id(socket_id)
unless custom_string.nil? || custom_string.kind_of?(String)
raise Error, 'Custom argument must be a string'
end
string_to_sign = [socket_id, name, custom_string].
compact.map(&:to_s).join(':')
Pusher.logger.debug "Signing #{string_to_sign}"
token = @client.authentication_token
digest = OpenSSL::Digest::SHA256.new
signature = OpenSSL::HMAC.hexdigest(digest, token.secret, string_to_sign)
return "#{token.key}:#{signature}"
end
|
ruby
|
def authentication_string(socket_id, custom_string = nil)
validate_socket_id(socket_id)
unless custom_string.nil? || custom_string.kind_of?(String)
raise Error, 'Custom argument must be a string'
end
string_to_sign = [socket_id, name, custom_string].
compact.map(&:to_s).join(':')
Pusher.logger.debug "Signing #{string_to_sign}"
token = @client.authentication_token
digest = OpenSSL::Digest::SHA256.new
signature = OpenSSL::HMAC.hexdigest(digest, token.secret, string_to_sign)
return "#{token.key}:#{signature}"
end
|
[
"def",
"authentication_string",
"(",
"socket_id",
",",
"custom_string",
"=",
"nil",
")",
"validate_socket_id",
"(",
"socket_id",
")",
"unless",
"custom_string",
".",
"nil?",
"||",
"custom_string",
".",
"kind_of?",
"(",
"String",
")",
"raise",
"Error",
",",
"'Custom argument must be a string'",
"end",
"string_to_sign",
"=",
"[",
"socket_id",
",",
"name",
",",
"custom_string",
"]",
".",
"compact",
".",
"map",
"(",
":to_s",
")",
".",
"join",
"(",
"':'",
")",
"Pusher",
".",
"logger",
".",
"debug",
"\"Signing #{string_to_sign}\"",
"token",
"=",
"@client",
".",
"authentication_token",
"digest",
"=",
"OpenSSL",
"::",
"Digest",
"::",
"SHA256",
".",
"new",
"signature",
"=",
"OpenSSL",
"::",
"HMAC",
".",
"hexdigest",
"(",
"digest",
",",
"token",
".",
"secret",
",",
"string_to_sign",
")",
"return",
"\"#{token.key}:#{signature}\"",
"end"
] |
Compute authentication string required as part of the authentication
endpoint response. Generally the authenticate method should be used in
preference to this one
@param socket_id [String] Each Pusher socket connection receives a
unique socket_id. This is sent from pusher.js to your server when
channel authentication is required.
@param custom_string [String] Allows signing additional data
@return [String]
@raise [Pusher::Error] if socket_id or custom_string invalid
|
[
"Compute",
"authentication",
"string",
"required",
"as",
"part",
"of",
"the",
"authentication",
"endpoint",
"response",
".",
"Generally",
"the",
"authenticate",
"method",
"should",
"be",
"used",
"in",
"preference",
"to",
"this",
"one"
] |
cd666ca74b39dacfae6ca0235c35fcf80eba1e64
|
https://github.com/pusher/pusher-http-ruby/blob/cd666ca74b39dacfae6ca0235c35fcf80eba1e64/lib/pusher/channel.rb#L128-L143
|
16,888
|
codevise/pageflow
|
lib/pageflow/widget_type.rb
|
Pageflow.WidgetType.render
|
def render(template, entry)
template.render(File.join('pageflow', name, 'widget'), entry: entry)
end
|
ruby
|
def render(template, entry)
template.render(File.join('pageflow', name, 'widget'), entry: entry)
end
|
[
"def",
"render",
"(",
"template",
",",
"entry",
")",
"template",
".",
"render",
"(",
"File",
".",
"join",
"(",
"'pageflow'",
",",
"name",
",",
"'widget'",
")",
",",
"entry",
":",
"entry",
")",
"end"
] |
Override to return html as string.
|
[
"Override",
"to",
"return",
"html",
"as",
"string",
"."
] |
08a812373823581f44aa59a95b83f0deb55f4ed9
|
https://github.com/codevise/pageflow/blob/08a812373823581f44aa59a95b83f0deb55f4ed9/lib/pageflow/widget_type.rb#L43-L45
|
16,889
|
codevise/pageflow
|
app/models/pageflow/account_role_query.rb
|
Pageflow.AccountRoleQuery.has_at_least_role?
|
def has_at_least_role?(role)
@user
.memberships
.where(role: Roles.at_least(role))
.where('(entity_id = :account_id AND '\
"entity_type = 'Pageflow::Account')",
account_id: @account.id)
.any?
end
|
ruby
|
def has_at_least_role?(role)
@user
.memberships
.where(role: Roles.at_least(role))
.where('(entity_id = :account_id AND '\
"entity_type = 'Pageflow::Account')",
account_id: @account.id)
.any?
end
|
[
"def",
"has_at_least_role?",
"(",
"role",
")",
"@user",
".",
"memberships",
".",
"where",
"(",
"role",
":",
"Roles",
".",
"at_least",
"(",
"role",
")",
")",
".",
"where",
"(",
"'(entity_id = :account_id AND '",
"\"entity_type = 'Pageflow::Account')\"",
",",
"account_id",
":",
"@account",
".",
"id",
")",
".",
"any?",
"end"
] |
Create query that can be used for role comparisons
@param [User] user
Required. Membership user to check.
@param [Pageflow::Account] account
Required. Membership entity to check.
Return true if there is a membership with at least role for
user/account
@param [String] role
Required. Minimum role that we compare against.
@return [Boolean]
|
[
"Create",
"query",
"that",
"can",
"be",
"used",
"for",
"role",
"comparisons"
] |
08a812373823581f44aa59a95b83f0deb55f4ed9
|
https://github.com/codevise/pageflow/blob/08a812373823581f44aa59a95b83f0deb55f4ed9/app/models/pageflow/account_role_query.rb#L58-L66
|
16,890
|
codevise/pageflow
|
lib/pageflow/help_entries.rb
|
Pageflow.HelpEntries.register
|
def register(name, options = {})
help_entry = HelpEntry.new(name, options)
@help_entries_by_name[name] = help_entry
collection = find_collection(options[:parent])
collection << help_entry
collection.sort_by! { |help_entry| -help_entry.priority }
end
|
ruby
|
def register(name, options = {})
help_entry = HelpEntry.new(name, options)
@help_entries_by_name[name] = help_entry
collection = find_collection(options[:parent])
collection << help_entry
collection.sort_by! { |help_entry| -help_entry.priority }
end
|
[
"def",
"register",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"help_entry",
"=",
"HelpEntry",
".",
"new",
"(",
"name",
",",
"options",
")",
"@help_entries_by_name",
"[",
"name",
"]",
"=",
"help_entry",
"collection",
"=",
"find_collection",
"(",
"options",
"[",
":parent",
"]",
")",
"collection",
"<<",
"help_entry",
"collection",
".",
"sort_by!",
"{",
"|",
"help_entry",
"|",
"-",
"help_entry",
".",
"priority",
"}",
"end"
] |
Add a section to the help dialog displayed in the editor.
Translation keys for the help entry are derived from its name by
appending ".menu_item" and ".text". Text is parsed as markdown.
@param [String] name Translation key prefix
@param [Hash] options
@option options [String] :parent Name of the parent help entry
@option options [Fixnum] :priority (10) Entries with higher
priority come first in the entry list.
|
[
"Add",
"a",
"section",
"to",
"the",
"help",
"dialog",
"displayed",
"in",
"the",
"editor",
"."
] |
08a812373823581f44aa59a95b83f0deb55f4ed9
|
https://github.com/codevise/pageflow/blob/08a812373823581f44aa59a95b83f0deb55f4ed9/lib/pageflow/help_entries.rb#L20-L28
|
16,891
|
twitchtv/twirp-ruby
|
lib/twirp/service.rb
|
Twirp.Service.call
|
def call(rack_env)
begin
env = {}
bad_route = route_request(rack_env, env)
return error_response(bad_route, env) if bad_route
@before.each do |hook|
result = hook.call(rack_env, env)
return error_response(result, env) if result.is_a? Twirp::Error
end
output = call_handler(env)
return error_response(output, env) if output.is_a? Twirp::Error
return success_response(output, env)
rescue => e
raise e if self.class.raise_exceptions
begin
@exception_raised.each{|hook| hook.call(e, env) }
rescue => hook_e
e = hook_e
end
twerr = Twirp::Error.internal_with(e)
return error_response(twerr, env)
end
end
|
ruby
|
def call(rack_env)
begin
env = {}
bad_route = route_request(rack_env, env)
return error_response(bad_route, env) if bad_route
@before.each do |hook|
result = hook.call(rack_env, env)
return error_response(result, env) if result.is_a? Twirp::Error
end
output = call_handler(env)
return error_response(output, env) if output.is_a? Twirp::Error
return success_response(output, env)
rescue => e
raise e if self.class.raise_exceptions
begin
@exception_raised.each{|hook| hook.call(e, env) }
rescue => hook_e
e = hook_e
end
twerr = Twirp::Error.internal_with(e)
return error_response(twerr, env)
end
end
|
[
"def",
"call",
"(",
"rack_env",
")",
"begin",
"env",
"=",
"{",
"}",
"bad_route",
"=",
"route_request",
"(",
"rack_env",
",",
"env",
")",
"return",
"error_response",
"(",
"bad_route",
",",
"env",
")",
"if",
"bad_route",
"@before",
".",
"each",
"do",
"|",
"hook",
"|",
"result",
"=",
"hook",
".",
"call",
"(",
"rack_env",
",",
"env",
")",
"return",
"error_response",
"(",
"result",
",",
"env",
")",
"if",
"result",
".",
"is_a?",
"Twirp",
"::",
"Error",
"end",
"output",
"=",
"call_handler",
"(",
"env",
")",
"return",
"error_response",
"(",
"output",
",",
"env",
")",
"if",
"output",
".",
"is_a?",
"Twirp",
"::",
"Error",
"return",
"success_response",
"(",
"output",
",",
"env",
")",
"rescue",
"=>",
"e",
"raise",
"e",
"if",
"self",
".",
"class",
".",
"raise_exceptions",
"begin",
"@exception_raised",
".",
"each",
"{",
"|",
"hook",
"|",
"hook",
".",
"call",
"(",
"e",
",",
"env",
")",
"}",
"rescue",
"=>",
"hook_e",
"e",
"=",
"hook_e",
"end",
"twerr",
"=",
"Twirp",
"::",
"Error",
".",
"internal_with",
"(",
"e",
")",
"return",
"error_response",
"(",
"twerr",
",",
"env",
")",
"end",
"end"
] |
Rack app handler.
|
[
"Rack",
"app",
"handler",
"."
] |
3ec36d2653a14eb8cc73409fb20889e8484db371
|
https://github.com/twitchtv/twirp-ruby/blob/3ec36d2653a14eb8cc73409fb20889e8484db371/lib/twirp/service.rb#L61-L87
|
16,892
|
twitchtv/twirp-ruby
|
lib/twirp/service.rb
|
Twirp.Service.route_request
|
def route_request(rack_env, env)
rack_request = Rack::Request.new(rack_env)
if rack_request.request_method != "POST"
return bad_route_error("HTTP request method must be POST", rack_request)
end
content_type = rack_request.get_header("CONTENT_TYPE")
if !Encoding.valid_content_type?(content_type)
return bad_route_error("Unexpected Content-Type: #{content_type.inspect}. Content-Type header must be one of #{Encoding.valid_content_types.inspect}", rack_request)
end
env[:content_type] = content_type
path_parts = rack_request.fullpath.split("/")
if path_parts.size < 3 || path_parts[-2] != self.full_name
return bad_route_error("Invalid route. Expected format: POST {BaseURL}/#{self.full_name}/{Method}", rack_request)
end
method_name = path_parts[-1]
base_env = self.class.rpcs[method_name]
if !base_env
return bad_route_error("Invalid rpc method #{method_name.inspect}", rack_request)
end
env.merge!(base_env) # :rpc_method, :input_class, :output_class
input = nil
begin
input = Encoding.decode(rack_request.body.read, env[:input_class], content_type)
rescue => e
error_msg = "Invalid request body for rpc method #{method_name.inspect} with Content-Type=#{content_type}"
if e.is_a?(Google::Protobuf::ParseError)
error_msg += ": #{e.message.strip}"
end
return bad_route_error(error_msg, rack_request)
end
env[:input] = input
env[:http_response_headers] = {}
return
end
|
ruby
|
def route_request(rack_env, env)
rack_request = Rack::Request.new(rack_env)
if rack_request.request_method != "POST"
return bad_route_error("HTTP request method must be POST", rack_request)
end
content_type = rack_request.get_header("CONTENT_TYPE")
if !Encoding.valid_content_type?(content_type)
return bad_route_error("Unexpected Content-Type: #{content_type.inspect}. Content-Type header must be one of #{Encoding.valid_content_types.inspect}", rack_request)
end
env[:content_type] = content_type
path_parts = rack_request.fullpath.split("/")
if path_parts.size < 3 || path_parts[-2] != self.full_name
return bad_route_error("Invalid route. Expected format: POST {BaseURL}/#{self.full_name}/{Method}", rack_request)
end
method_name = path_parts[-1]
base_env = self.class.rpcs[method_name]
if !base_env
return bad_route_error("Invalid rpc method #{method_name.inspect}", rack_request)
end
env.merge!(base_env) # :rpc_method, :input_class, :output_class
input = nil
begin
input = Encoding.decode(rack_request.body.read, env[:input_class], content_type)
rescue => e
error_msg = "Invalid request body for rpc method #{method_name.inspect} with Content-Type=#{content_type}"
if e.is_a?(Google::Protobuf::ParseError)
error_msg += ": #{e.message.strip}"
end
return bad_route_error(error_msg, rack_request)
end
env[:input] = input
env[:http_response_headers] = {}
return
end
|
[
"def",
"route_request",
"(",
"rack_env",
",",
"env",
")",
"rack_request",
"=",
"Rack",
"::",
"Request",
".",
"new",
"(",
"rack_env",
")",
"if",
"rack_request",
".",
"request_method",
"!=",
"\"POST\"",
"return",
"bad_route_error",
"(",
"\"HTTP request method must be POST\"",
",",
"rack_request",
")",
"end",
"content_type",
"=",
"rack_request",
".",
"get_header",
"(",
"\"CONTENT_TYPE\"",
")",
"if",
"!",
"Encoding",
".",
"valid_content_type?",
"(",
"content_type",
")",
"return",
"bad_route_error",
"(",
"\"Unexpected Content-Type: #{content_type.inspect}. Content-Type header must be one of #{Encoding.valid_content_types.inspect}\"",
",",
"rack_request",
")",
"end",
"env",
"[",
":content_type",
"]",
"=",
"content_type",
"path_parts",
"=",
"rack_request",
".",
"fullpath",
".",
"split",
"(",
"\"/\"",
")",
"if",
"path_parts",
".",
"size",
"<",
"3",
"||",
"path_parts",
"[",
"-",
"2",
"]",
"!=",
"self",
".",
"full_name",
"return",
"bad_route_error",
"(",
"\"Invalid route. Expected format: POST {BaseURL}/#{self.full_name}/{Method}\"",
",",
"rack_request",
")",
"end",
"method_name",
"=",
"path_parts",
"[",
"-",
"1",
"]",
"base_env",
"=",
"self",
".",
"class",
".",
"rpcs",
"[",
"method_name",
"]",
"if",
"!",
"base_env",
"return",
"bad_route_error",
"(",
"\"Invalid rpc method #{method_name.inspect}\"",
",",
"rack_request",
")",
"end",
"env",
".",
"merge!",
"(",
"base_env",
")",
"# :rpc_method, :input_class, :output_class",
"input",
"=",
"nil",
"begin",
"input",
"=",
"Encoding",
".",
"decode",
"(",
"rack_request",
".",
"body",
".",
"read",
",",
"env",
"[",
":input_class",
"]",
",",
"content_type",
")",
"rescue",
"=>",
"e",
"error_msg",
"=",
"\"Invalid request body for rpc method #{method_name.inspect} with Content-Type=#{content_type}\"",
"if",
"e",
".",
"is_a?",
"(",
"Google",
"::",
"Protobuf",
"::",
"ParseError",
")",
"error_msg",
"+=",
"\": #{e.message.strip}\"",
"end",
"return",
"bad_route_error",
"(",
"error_msg",
",",
"rack_request",
")",
"end",
"env",
"[",
":input",
"]",
"=",
"input",
"env",
"[",
":http_response_headers",
"]",
"=",
"{",
"}",
"return",
"end"
] |
Parse request and fill env with rpc data.
Returns a bad_route error if something went wrong.
|
[
"Parse",
"request",
"and",
"fill",
"env",
"with",
"rpc",
"data",
".",
"Returns",
"a",
"bad_route",
"error",
"if",
"something",
"went",
"wrong",
"."
] |
3ec36d2653a14eb8cc73409fb20889e8484db371
|
https://github.com/twitchtv/twirp-ruby/blob/3ec36d2653a14eb8cc73409fb20889e8484db371/lib/twirp/service.rb#L111-L150
|
16,893
|
twitchtv/twirp-ruby
|
lib/twirp/service_dsl.rb
|
Twirp.ServiceDSL.rpc
|
def rpc(rpc_method, input_class, output_class, opts)
raise ArgumentError.new("rpc_method can not be empty") if rpc_method.to_s.empty?
raise ArgumentError.new("input_class must be a Protobuf Message class") unless input_class.is_a?(Class)
raise ArgumentError.new("output_class must be a Protobuf Message class") unless output_class.is_a?(Class)
raise ArgumentError.new("opts[:ruby_method] is mandatory") unless opts && opts[:ruby_method]
rpcdef = {
rpc_method: rpc_method.to_sym, # as defined in the Proto file.
input_class: input_class, # google/protobuf Message class to serialize the input (proto request).
output_class: output_class, # google/protobuf Message class to serialize the output (proto response).
ruby_method: opts[:ruby_method].to_sym, # method on the handler or client to handle this rpc requests.
}
@rpcs ||= {}
@rpcs[rpc_method.to_s] = rpcdef
rpc_define_method(rpcdef) if respond_to? :rpc_define_method # hook for the client to implement the methods on the class
end
|
ruby
|
def rpc(rpc_method, input_class, output_class, opts)
raise ArgumentError.new("rpc_method can not be empty") if rpc_method.to_s.empty?
raise ArgumentError.new("input_class must be a Protobuf Message class") unless input_class.is_a?(Class)
raise ArgumentError.new("output_class must be a Protobuf Message class") unless output_class.is_a?(Class)
raise ArgumentError.new("opts[:ruby_method] is mandatory") unless opts && opts[:ruby_method]
rpcdef = {
rpc_method: rpc_method.to_sym, # as defined in the Proto file.
input_class: input_class, # google/protobuf Message class to serialize the input (proto request).
output_class: output_class, # google/protobuf Message class to serialize the output (proto response).
ruby_method: opts[:ruby_method].to_sym, # method on the handler or client to handle this rpc requests.
}
@rpcs ||= {}
@rpcs[rpc_method.to_s] = rpcdef
rpc_define_method(rpcdef) if respond_to? :rpc_define_method # hook for the client to implement the methods on the class
end
|
[
"def",
"rpc",
"(",
"rpc_method",
",",
"input_class",
",",
"output_class",
",",
"opts",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"rpc_method can not be empty\"",
")",
"if",
"rpc_method",
".",
"to_s",
".",
"empty?",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"input_class must be a Protobuf Message class\"",
")",
"unless",
"input_class",
".",
"is_a?",
"(",
"Class",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"output_class must be a Protobuf Message class\"",
")",
"unless",
"output_class",
".",
"is_a?",
"(",
"Class",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"opts[:ruby_method] is mandatory\"",
")",
"unless",
"opts",
"&&",
"opts",
"[",
":ruby_method",
"]",
"rpcdef",
"=",
"{",
"rpc_method",
":",
"rpc_method",
".",
"to_sym",
",",
"# as defined in the Proto file.",
"input_class",
":",
"input_class",
",",
"# google/protobuf Message class to serialize the input (proto request).",
"output_class",
":",
"output_class",
",",
"# google/protobuf Message class to serialize the output (proto response).",
"ruby_method",
":",
"opts",
"[",
":ruby_method",
"]",
".",
"to_sym",
",",
"# method on the handler or client to handle this rpc requests.",
"}",
"@rpcs",
"||=",
"{",
"}",
"@rpcs",
"[",
"rpc_method",
".",
"to_s",
"]",
"=",
"rpcdef",
"rpc_define_method",
"(",
"rpcdef",
")",
"if",
"respond_to?",
":rpc_define_method",
"# hook for the client to implement the methods on the class",
"end"
] |
Configure service rpc methods.
|
[
"Configure",
"service",
"rpc",
"methods",
"."
] |
3ec36d2653a14eb8cc73409fb20889e8484db371
|
https://github.com/twitchtv/twirp-ruby/blob/3ec36d2653a14eb8cc73409fb20889e8484db371/lib/twirp/service_dsl.rb#L29-L46
|
16,894
|
copiousfreetime/launchy
|
lib/launchy/descendant_tracker.rb
|
Launchy.DescendantTracker.find_child
|
def find_child( method, *args )
children.find do |child|
Launchy.log "Checking if class #{child} is the one for #{method}(#{args.join(', ')})}"
child.send( method, *args )
end
end
|
ruby
|
def find_child( method, *args )
children.find do |child|
Launchy.log "Checking if class #{child} is the one for #{method}(#{args.join(', ')})}"
child.send( method, *args )
end
end
|
[
"def",
"find_child",
"(",
"method",
",",
"*",
"args",
")",
"children",
".",
"find",
"do",
"|",
"child",
"|",
"Launchy",
".",
"log",
"\"Checking if class #{child} is the one for #{method}(#{args.join(', ')})}\"",
"child",
".",
"send",
"(",
"method",
",",
"args",
")",
"end",
"end"
] |
Find one of the child classes by calling the given method
and passing all the rest of the parameters to that method in
each child
|
[
"Find",
"one",
"of",
"the",
"child",
"classes",
"by",
"calling",
"the",
"given",
"method",
"and",
"passing",
"all",
"the",
"rest",
"of",
"the",
"parameters",
"to",
"that",
"method",
"in",
"each",
"child"
] |
7983dbfb48229e909eb3c228c3c205715cab2365
|
https://github.com/copiousfreetime/launchy/blob/7983dbfb48229e909eb3c228c3c205715cab2365/lib/launchy/descendant_tracker.rb#L42-L47
|
16,895
|
TwP/logging
|
lib/rspec/logging_helper.rb
|
RSpec.LoggingHelper.capture_log_messages
|
def capture_log_messages( opts = {} )
from = opts.fetch(:from, 'root')
to = opts.fetch(:to, '__rspec__')
exclusive = opts.fetch(:exclusive, true)
appender = Logging::Appenders[to] || Logging::Appenders::StringIo.new(to)
logger = Logging::Logger[from]
if exclusive
logger.appenders = appender
else
logger.add_appenders(appender)
end
before(:all) do
@log_output = Logging::Appenders[to]
end
before(:each) do
@log_output.reset
end
end
|
ruby
|
def capture_log_messages( opts = {} )
from = opts.fetch(:from, 'root')
to = opts.fetch(:to, '__rspec__')
exclusive = opts.fetch(:exclusive, true)
appender = Logging::Appenders[to] || Logging::Appenders::StringIo.new(to)
logger = Logging::Logger[from]
if exclusive
logger.appenders = appender
else
logger.add_appenders(appender)
end
before(:all) do
@log_output = Logging::Appenders[to]
end
before(:each) do
@log_output.reset
end
end
|
[
"def",
"capture_log_messages",
"(",
"opts",
"=",
"{",
"}",
")",
"from",
"=",
"opts",
".",
"fetch",
"(",
":from",
",",
"'root'",
")",
"to",
"=",
"opts",
".",
"fetch",
"(",
":to",
",",
"'__rspec__'",
")",
"exclusive",
"=",
"opts",
".",
"fetch",
"(",
":exclusive",
",",
"true",
")",
"appender",
"=",
"Logging",
"::",
"Appenders",
"[",
"to",
"]",
"||",
"Logging",
"::",
"Appenders",
"::",
"StringIo",
".",
"new",
"(",
"to",
")",
"logger",
"=",
"Logging",
"::",
"Logger",
"[",
"from",
"]",
"if",
"exclusive",
"logger",
".",
"appenders",
"=",
"appender",
"else",
"logger",
".",
"add_appenders",
"(",
"appender",
")",
"end",
"before",
"(",
":all",
")",
"do",
"@log_output",
"=",
"Logging",
"::",
"Appenders",
"[",
"to",
"]",
"end",
"before",
"(",
":each",
")",
"do",
"@log_output",
".",
"reset",
"end",
"end"
] |
Capture log messages from the Logging framework and make them
available via a @log_output instance variable. The @log_output
supports a readline method to access the log messages.
|
[
"Capture",
"log",
"messages",
"from",
"the",
"Logging",
"framework",
"and",
"make",
"them",
"available",
"via",
"a"
] |
aa9a5b840479f4176504e4c53ce29d8d01315ccc
|
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/rspec/logging_helper.rb#L9-L29
|
16,896
|
TwP/logging
|
lib/logging/repository.rb
|
Logging.Repository.parent_name
|
def parent_name( key )
return if :root == key
a = key.split PATH_DELIMITER
p = :root
while a.slice!(-1) and !a.empty?
k = a.join PATH_DELIMITER
if @h.has_key? k then p = k; break end
end
p
end
|
ruby
|
def parent_name( key )
return if :root == key
a = key.split PATH_DELIMITER
p = :root
while a.slice!(-1) and !a.empty?
k = a.join PATH_DELIMITER
if @h.has_key? k then p = k; break end
end
p
end
|
[
"def",
"parent_name",
"(",
"key",
")",
"return",
"if",
":root",
"==",
"key",
"a",
"=",
"key",
".",
"split",
"PATH_DELIMITER",
"p",
"=",
":root",
"while",
"a",
".",
"slice!",
"(",
"-",
"1",
")",
"and",
"!",
"a",
".",
"empty?",
"k",
"=",
"a",
".",
"join",
"PATH_DELIMITER",
"if",
"@h",
".",
"has_key?",
"k",
"then",
"p",
"=",
"k",
";",
"break",
"end",
"end",
"p",
"end"
] |
Returns the name of the parent for the logger identified by the given
_key_. If the _key_ is for the root logger, then +nil+ is returned.
|
[
"Returns",
"the",
"name",
"of",
"the",
"parent",
"for",
"the",
"logger",
"identified",
"by",
"the",
"given",
"_key_",
".",
"If",
"the",
"_key_",
"is",
"for",
"the",
"root",
"logger",
"then",
"+",
"nil",
"+",
"is",
"returned",
"."
] |
aa9a5b840479f4176504e4c53ce29d8d01315ccc
|
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/repository.rb#L180-L190
|
16,897
|
TwP/logging
|
lib/logging/appenders/rolling_file.rb
|
Logging::Appenders.RollingFile.build_singleton_methods
|
def build_singleton_methods
method =
case @age
when 'daily'
-> {
now = Time.now
(now.day != age_fn_mtime.day) || (now - age_fn_mtime) > 86400
}
when 'weekly'
-> { (Time.now - age_fn_mtime) > 604800 }
when 'monthly'
-> {
now = Time.now
(now.month != age_fn_mtime.month) || (now - age_fn_mtime) > 2678400
}
when Integer, String
@age = Integer(@age)
-> { (Time.now - age_fn_mtime) > @age }
else
-> { false }
end
self.define_singleton_method(:sufficiently_aged?, method)
end
|
ruby
|
def build_singleton_methods
method =
case @age
when 'daily'
-> {
now = Time.now
(now.day != age_fn_mtime.day) || (now - age_fn_mtime) > 86400
}
when 'weekly'
-> { (Time.now - age_fn_mtime) > 604800 }
when 'monthly'
-> {
now = Time.now
(now.month != age_fn_mtime.month) || (now - age_fn_mtime) > 2678400
}
when Integer, String
@age = Integer(@age)
-> { (Time.now - age_fn_mtime) > @age }
else
-> { false }
end
self.define_singleton_method(:sufficiently_aged?, method)
end
|
[
"def",
"build_singleton_methods",
"method",
"=",
"case",
"@age",
"when",
"'daily'",
"->",
"{",
"now",
"=",
"Time",
".",
"now",
"(",
"now",
".",
"day",
"!=",
"age_fn_mtime",
".",
"day",
")",
"||",
"(",
"now",
"-",
"age_fn_mtime",
")",
">",
"86400",
"}",
"when",
"'weekly'",
"->",
"{",
"(",
"Time",
".",
"now",
"-",
"age_fn_mtime",
")",
">",
"604800",
"}",
"when",
"'monthly'",
"->",
"{",
"now",
"=",
"Time",
".",
"now",
"(",
"now",
".",
"month",
"!=",
"age_fn_mtime",
".",
"month",
")",
"||",
"(",
"now",
"-",
"age_fn_mtime",
")",
">",
"2678400",
"}",
"when",
"Integer",
",",
"String",
"@age",
"=",
"Integer",
"(",
"@age",
")",
"->",
"{",
"(",
"Time",
".",
"now",
"-",
"age_fn_mtime",
")",
">",
"@age",
"}",
"else",
"->",
"{",
"false",
"}",
"end",
"self",
".",
"define_singleton_method",
"(",
":sufficiently_aged?",
",",
"method",
")",
"end"
] |
We use meta-programming here to define the `sufficiently_aged?` method for
the rolling appender. The `sufficiently_aged?` method is responsible for
determining if the current log file is older than the rolling criteria -
daily, weekly, etc.
Returns this rolling file appender instance
|
[
"We",
"use",
"meta",
"-",
"programming",
"here",
"to",
"define",
"the",
"sufficiently_aged?",
"method",
"for",
"the",
"rolling",
"appender",
".",
"The",
"sufficiently_aged?",
"method",
"is",
"responsible",
"for",
"determining",
"if",
"the",
"current",
"log",
"file",
"is",
"older",
"than",
"the",
"rolling",
"criteria",
"-",
"daily",
"weekly",
"etc",
"."
] |
aa9a5b840479f4176504e4c53ce29d8d01315ccc
|
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/appenders/rolling_file.rb#L218-L245
|
16,898
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
Logging::Appenders.Buffering.auto_flushing=
|
def auto_flushing=( period )
@auto_flushing =
case period
when true; 1
when false, nil, 0; DEFAULT_BUFFER_SIZE
when Integer; period
when String; Integer(period)
else
raise ArgumentError,
"unrecognized auto_flushing period: #{period.inspect}"
end
if @auto_flushing <= 0
raise ArgumentError,
"auto_flushing period must be greater than zero: #{period.inspect}"
end
@auto_flushing = DEFAULT_BUFFER_SIZE if @flush_period && @auto_flushing <= 1
end
|
ruby
|
def auto_flushing=( period )
@auto_flushing =
case period
when true; 1
when false, nil, 0; DEFAULT_BUFFER_SIZE
when Integer; period
when String; Integer(period)
else
raise ArgumentError,
"unrecognized auto_flushing period: #{period.inspect}"
end
if @auto_flushing <= 0
raise ArgumentError,
"auto_flushing period must be greater than zero: #{period.inspect}"
end
@auto_flushing = DEFAULT_BUFFER_SIZE if @flush_period && @auto_flushing <= 1
end
|
[
"def",
"auto_flushing",
"=",
"(",
"period",
")",
"@auto_flushing",
"=",
"case",
"period",
"when",
"true",
";",
"1",
"when",
"false",
",",
"nil",
",",
"0",
";",
"DEFAULT_BUFFER_SIZE",
"when",
"Integer",
";",
"period",
"when",
"String",
";",
"Integer",
"(",
"period",
")",
"else",
"raise",
"ArgumentError",
",",
"\"unrecognized auto_flushing period: #{period.inspect}\"",
"end",
"if",
"@auto_flushing",
"<=",
"0",
"raise",
"ArgumentError",
",",
"\"auto_flushing period must be greater than zero: #{period.inspect}\"",
"end",
"@auto_flushing",
"=",
"DEFAULT_BUFFER_SIZE",
"if",
"@flush_period",
"&&",
"@auto_flushing",
"<=",
"1",
"end"
] |
Configure the auto-flushing threshold. Auto-flushing is used to flush
the contents of the logging buffer to the logging destination
automatically when the buffer reaches a certain threshold.
By default, the auto-flushing will be configured to flush after each
log message.
The allowed settings are as follows:
N : flush after every N messages (N is an integer)
true : flush after each log message
false OR
nil OR
0 : only flush when the buffer is full (500 messages)
If the default buffer size of 500 is too small, then you can manually
configure it to be as large as you want. This will consume more memory.
auto_flushing = 42_000
|
[
"Configure",
"the",
"auto",
"-",
"flushing",
"threshold",
".",
"Auto",
"-",
"flushing",
"is",
"used",
"to",
"flush",
"the",
"contents",
"of",
"the",
"logging",
"buffer",
"to",
"the",
"logging",
"destination",
"automatically",
"when",
"the",
"buffer",
"reaches",
"a",
"certain",
"threshold",
"."
] |
aa9a5b840479f4176504e4c53ce29d8d01315ccc
|
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/appenders/buffering.rb#L160-L178
|
16,899
|
TwP/logging
|
lib/logging/appenders/buffering.rb
|
Logging::Appenders.Buffering._setup_async_flusher
|
def _setup_async_flusher
# stop and remove any existing async flusher instance
if @async_flusher
@async_flusher.stop
@async_flusher = nil
Thread.pass
end
# create a new async flusher if we have a valid flush period
if @flush_period || async?
@auto_flushing = DEFAULT_BUFFER_SIZE unless @auto_flushing > 1
@async_flusher = AsyncFlusher.new(self, @flush_period)
@async_flusher.start
Thread.pass
end
nil
end
|
ruby
|
def _setup_async_flusher
# stop and remove any existing async flusher instance
if @async_flusher
@async_flusher.stop
@async_flusher = nil
Thread.pass
end
# create a new async flusher if we have a valid flush period
if @flush_period || async?
@auto_flushing = DEFAULT_BUFFER_SIZE unless @auto_flushing > 1
@async_flusher = AsyncFlusher.new(self, @flush_period)
@async_flusher.start
Thread.pass
end
nil
end
|
[
"def",
"_setup_async_flusher",
"# stop and remove any existing async flusher instance",
"if",
"@async_flusher",
"@async_flusher",
".",
"stop",
"@async_flusher",
"=",
"nil",
"Thread",
".",
"pass",
"end",
"# create a new async flusher if we have a valid flush period",
"if",
"@flush_period",
"||",
"async?",
"@auto_flushing",
"=",
"DEFAULT_BUFFER_SIZE",
"unless",
"@auto_flushing",
">",
"1",
"@async_flusher",
"=",
"AsyncFlusher",
".",
"new",
"(",
"self",
",",
"@flush_period",
")",
"@async_flusher",
".",
"start",
"Thread",
".",
"pass",
"end",
"nil",
"end"
] |
Using the flush_period, create a new AsyncFlusher attached to this
appender. If the flush_period is nil, then no action will be taken. If a
AsyncFlusher already exists, it will be stopped and a new one will be
created.
Returns `nil`
|
[
"Using",
"the",
"flush_period",
"create",
"a",
"new",
"AsyncFlusher",
"attached",
"to",
"this",
"appender",
".",
"If",
"the",
"flush_period",
"is",
"nil",
"then",
"no",
"action",
"will",
"be",
"taken",
".",
"If",
"a",
"AsyncFlusher",
"already",
"exists",
"it",
"will",
"be",
"stopped",
"and",
"a",
"new",
"one",
"will",
"be",
"created",
"."
] |
aa9a5b840479f4176504e4c53ce29d8d01315ccc
|
https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/appenders/buffering.rb#L347-L364
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.