repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
activescaffold/active_scaffold | lib/active_scaffold/data_structures/sorting.rb | ActiveScaffold::DataStructures.Sorting.clause | def clause(grouped_columns_calculations = nil)
return nil if sorts_by_method? || default_sorting?
# unless the sorting is by method, create the sql string
order = []
each do |sort_column, sort_direction|
next if constraint_columns.include? sort_column.name
sql = grouped_columns_calculations&.dig(sort_column.name) || sort_column.sort[:sql]
next if sql.blank?
sql = sql.to_sql if sql.respond_to?(:to_sql)
parts = Array(sql).map do |column|
mongoid? ? [column, sort_direction] : "#{column} #{sort_direction}"
end
order << parts
end
order << @primary_key_order_clause if @sorting_by_primary_key
order.flatten!(1)
order unless order.empty?
end | ruby | def clause(grouped_columns_calculations = nil)
return nil if sorts_by_method? || default_sorting?
# unless the sorting is by method, create the sql string
order = []
each do |sort_column, sort_direction|
next if constraint_columns.include? sort_column.name
sql = grouped_columns_calculations&.dig(sort_column.name) || sort_column.sort[:sql]
next if sql.blank?
sql = sql.to_sql if sql.respond_to?(:to_sql)
parts = Array(sql).map do |column|
mongoid? ? [column, sort_direction] : "#{column} #{sort_direction}"
end
order << parts
end
order << @primary_key_order_clause if @sorting_by_primary_key
order.flatten!(1)
order unless order.empty?
end | [
"def",
"clause",
"(",
"grouped_columns_calculations",
"=",
"nil",
")",
"return",
"nil",
"if",
"sorts_by_method?",
"||",
"default_sorting?",
"# unless the sorting is by method, create the sql string",
"order",
"=",
"[",
"]",
"each",
"do",
"|",
"sort_column",
",",
"sort_direction",
"|",
"next",
"if",
"constraint_columns",
".",
"include?",
"sort_column",
".",
"name",
"sql",
"=",
"grouped_columns_calculations",
"&.",
"dig",
"(",
"sort_column",
".",
"name",
")",
"||",
"sort_column",
".",
"sort",
"[",
":sql",
"]",
"next",
"if",
"sql",
".",
"blank?",
"sql",
"=",
"sql",
".",
"to_sql",
"if",
"sql",
".",
"respond_to?",
"(",
":to_sql",
")",
"parts",
"=",
"Array",
"(",
"sql",
")",
".",
"map",
"do",
"|",
"column",
"|",
"mongoid?",
"?",
"[",
"column",
",",
"sort_direction",
"]",
":",
"\"#{column} #{sort_direction}\"",
"end",
"order",
"<<",
"parts",
"end",
"order",
"<<",
"@primary_key_order_clause",
"if",
"@sorting_by_primary_key",
"order",
".",
"flatten!",
"(",
"1",
")",
"order",
"unless",
"order",
".",
"empty?",
"end"
] | builds an order-by clause | [
"builds",
"an",
"order",
"-",
"by",
"clause"
] | 1954f85b5395d09de09fa86f3ea70c29bbee2612 | https://github.com/activescaffold/active_scaffold/blob/1954f85b5395d09de09fa86f3ea70c29bbee2612/lib/active_scaffold/data_structures/sorting.rb#L123-L143 | train |
activescaffold/active_scaffold | lib/active_scaffold/data_structures/sorting.rb | ActiveScaffold::DataStructures.Sorting.get_column | def get_column(name_or_column)
# it's a column
return name_or_column if name_or_column.is_a? ActiveScaffold::DataStructures::Column
# it's a name
name_or_column = name_or_column.to_s.split('.').last if name_or_column.to_s.include? '.'
@columns[name_or_column]
end | ruby | def get_column(name_or_column)
# it's a column
return name_or_column if name_or_column.is_a? ActiveScaffold::DataStructures::Column
# it's a name
name_or_column = name_or_column.to_s.split('.').last if name_or_column.to_s.include? '.'
@columns[name_or_column]
end | [
"def",
"get_column",
"(",
"name_or_column",
")",
"# it's a column",
"return",
"name_or_column",
"if",
"name_or_column",
".",
"is_a?",
"ActiveScaffold",
"::",
"DataStructures",
"::",
"Column",
"# it's a name",
"name_or_column",
"=",
"name_or_column",
".",
"to_s",
".",
"split",
"(",
"'.'",
")",
".",
"last",
"if",
"name_or_column",
".",
"to_s",
".",
"include?",
"'.'",
"@columns",
"[",
"name_or_column",
"]",
"end"
] | possibly converts the given argument into a column object from @columns (if it's not already) | [
"possibly",
"converts",
"the",
"given",
"argument",
"into",
"a",
"column",
"object",
"from"
] | 1954f85b5395d09de09fa86f3ea70c29bbee2612 | https://github.com/activescaffold/active_scaffold/blob/1954f85b5395d09de09fa86f3ea70c29bbee2612/lib/active_scaffold/data_structures/sorting.rb#L154-L160 | train |
activescaffold/active_scaffold | lib/active_scaffold/data_structures/columns.rb | ActiveScaffold::DataStructures.Columns.add | def add(*args)
args.flatten! # allow [] as a param
args = args.collect(&:to_sym)
# make the columns inheritable
@_inheritable.concat(args)
# then add columns to @set (unless they already exist)
args.each { |a| @set << ActiveScaffold::DataStructures::Column.new(a.to_sym, @active_record_class) unless find_by_name(a) }
end | ruby | def add(*args)
args.flatten! # allow [] as a param
args = args.collect(&:to_sym)
# make the columns inheritable
@_inheritable.concat(args)
# then add columns to @set (unless they already exist)
args.each { |a| @set << ActiveScaffold::DataStructures::Column.new(a.to_sym, @active_record_class) unless find_by_name(a) }
end | [
"def",
"add",
"(",
"*",
"args",
")",
"args",
".",
"flatten!",
"# allow [] as a param",
"args",
"=",
"args",
".",
"collect",
"(",
":to_sym",
")",
"# make the columns inheritable",
"@_inheritable",
".",
"concat",
"(",
"args",
")",
"# then add columns to @set (unless they already exist)",
"args",
".",
"each",
"{",
"|",
"a",
"|",
"@set",
"<<",
"ActiveScaffold",
"::",
"DataStructures",
"::",
"Column",
".",
"new",
"(",
"a",
".",
"to_sym",
",",
"@active_record_class",
")",
"unless",
"find_by_name",
"(",
"a",
")",
"}",
"end"
] | the way to add columns to the set. this is primarily useful for virtual columns.
note that this also makes columns inheritable | [
"the",
"way",
"to",
"add",
"columns",
"to",
"the",
"set",
".",
"this",
"is",
"primarily",
"useful",
"for",
"virtual",
"columns",
".",
"note",
"that",
"this",
"also",
"makes",
"columns",
"inheritable"
] | 1954f85b5395d09de09fa86f3ea70c29bbee2612 | https://github.com/activescaffold/active_scaffold/blob/1954f85b5395d09de09fa86f3ea70c29bbee2612/lib/active_scaffold/data_structures/columns.rb#L32-L40 | train |
activescaffold/active_scaffold | lib/active_scaffold/data_structures/column.rb | ActiveScaffold::DataStructures.Column.set_link | def set_link(action, options = {})
if action.is_a?(ActiveScaffold::DataStructures::ActionLink) || (action.is_a? Proc)
@link = action
else
options[:label] ||= label
options[:position] ||= :after unless options.key?(:position)
options[:type] ||= :member
@link = ActiveScaffold::DataStructures::ActionLink.new(action, options)
end
end | ruby | def set_link(action, options = {})
if action.is_a?(ActiveScaffold::DataStructures::ActionLink) || (action.is_a? Proc)
@link = action
else
options[:label] ||= label
options[:position] ||= :after unless options.key?(:position)
options[:type] ||= :member
@link = ActiveScaffold::DataStructures::ActionLink.new(action, options)
end
end | [
"def",
"set_link",
"(",
"action",
",",
"options",
"=",
"{",
"}",
")",
"if",
"action",
".",
"is_a?",
"(",
"ActiveScaffold",
"::",
"DataStructures",
"::",
"ActionLink",
")",
"||",
"(",
"action",
".",
"is_a?",
"Proc",
")",
"@link",
"=",
"action",
"else",
"options",
"[",
":label",
"]",
"||=",
"label",
"options",
"[",
":position",
"]",
"||=",
":after",
"unless",
"options",
".",
"key?",
"(",
":position",
")",
"options",
"[",
":type",
"]",
"||=",
":member",
"@link",
"=",
"ActiveScaffold",
"::",
"DataStructures",
"::",
"ActionLink",
".",
"new",
"(",
"action",
",",
"options",
")",
"end",
"end"
] | associate an action_link with this column | [
"associate",
"an",
"action_link",
"with",
"this",
"column"
] | 1954f85b5395d09de09fa86f3ea70c29bbee2612 | https://github.com/activescaffold/active_scaffold/blob/1954f85b5395d09de09fa86f3ea70c29bbee2612/lib/active_scaffold/data_structures/column.rb#L156-L165 | train |
activescaffold/active_scaffold | lib/active_scaffold/data_structures/action_links.rb | ActiveScaffold::DataStructures.ActionLinks.add | def add(action, options = {})
link =
if action.is_a?(ActiveScaffold::DataStructures::ActionLink) || action.is_a?(ActiveScaffold::DataStructures::ActionLinks)
action
else
options[:type] ||= default_type if default_type
ActiveScaffold::DataStructures::ActionLink.new(action, options)
end
# NOTE: this duplicate check should be done by defining the comparison operator for an Action data structure
existing = find_duplicate(link)
if existing
existing
else
# That s for backwards compatibility if we are in root of action_links
# we have to move actionlink into members or collection subgroup
group = (name == :root ? subgroup(link.type, link.type) : self)
group.add_to_set(link)
link
end
end | ruby | def add(action, options = {})
link =
if action.is_a?(ActiveScaffold::DataStructures::ActionLink) || action.is_a?(ActiveScaffold::DataStructures::ActionLinks)
action
else
options[:type] ||= default_type if default_type
ActiveScaffold::DataStructures::ActionLink.new(action, options)
end
# NOTE: this duplicate check should be done by defining the comparison operator for an Action data structure
existing = find_duplicate(link)
if existing
existing
else
# That s for backwards compatibility if we are in root of action_links
# we have to move actionlink into members or collection subgroup
group = (name == :root ? subgroup(link.type, link.type) : self)
group.add_to_set(link)
link
end
end | [
"def",
"add",
"(",
"action",
",",
"options",
"=",
"{",
"}",
")",
"link",
"=",
"if",
"action",
".",
"is_a?",
"(",
"ActiveScaffold",
"::",
"DataStructures",
"::",
"ActionLink",
")",
"||",
"action",
".",
"is_a?",
"(",
"ActiveScaffold",
"::",
"DataStructures",
"::",
"ActionLinks",
")",
"action",
"else",
"options",
"[",
":type",
"]",
"||=",
"default_type",
"if",
"default_type",
"ActiveScaffold",
"::",
"DataStructures",
"::",
"ActionLink",
".",
"new",
"(",
"action",
",",
"options",
")",
"end",
"# NOTE: this duplicate check should be done by defining the comparison operator for an Action data structure",
"existing",
"=",
"find_duplicate",
"(",
"link",
")",
"if",
"existing",
"existing",
"else",
"# That s for backwards compatibility if we are in root of action_links",
"# we have to move actionlink into members or collection subgroup",
"group",
"=",
"(",
"name",
"==",
":root",
"?",
"subgroup",
"(",
"link",
".",
"type",
",",
"link",
".",
"type",
")",
":",
"self",
")",
"group",
".",
"add_to_set",
"(",
"link",
")",
"link",
"end",
"end"
] | adds an ActionLink, creating one from the arguments if need be | [
"adds",
"an",
"ActionLink",
"creating",
"one",
"from",
"the",
"arguments",
"if",
"need",
"be"
] | 1954f85b5395d09de09fa86f3ea70c29bbee2612 | https://github.com/activescaffold/active_scaffold/blob/1954f85b5395d09de09fa86f3ea70c29bbee2612/lib/active_scaffold/data_structures/action_links.rb#L13-L33 | train |
activescaffold/active_scaffold | lib/active_scaffold/data_structures/action_links.rb | ActiveScaffold::DataStructures.ActionLinks.add_to_group | def add_to_group(link, group_name = nil)
add_to = root
add_to = group_name.split('.').inject(root) { |group, name| group.send(name) } if group_name
add_to << link unless link.nil?
end | ruby | def add_to_group(link, group_name = nil)
add_to = root
add_to = group_name.split('.').inject(root) { |group, name| group.send(name) } if group_name
add_to << link unless link.nil?
end | [
"def",
"add_to_group",
"(",
"link",
",",
"group_name",
"=",
"nil",
")",
"add_to",
"=",
"root",
"add_to",
"=",
"group_name",
".",
"split",
"(",
"'.'",
")",
".",
"inject",
"(",
"root",
")",
"{",
"|",
"group",
",",
"name",
"|",
"group",
".",
"send",
"(",
"name",
")",
"}",
"if",
"group_name",
"add_to",
"<<",
"link",
"unless",
"link",
".",
"nil?",
"end"
] | adds a link to a specific group
groups are represented as a string separated by a dot
eg member.crud | [
"adds",
"a",
"link",
"to",
"a",
"specific",
"group",
"groups",
"are",
"represented",
"as",
"a",
"string",
"separated",
"by",
"a",
"dot",
"eg",
"member",
".",
"crud"
] | 1954f85b5395d09de09fa86f3ea70c29bbee2612 | https://github.com/activescaffold/active_scaffold/blob/1954f85b5395d09de09fa86f3ea70c29bbee2612/lib/active_scaffold/data_structures/action_links.rb#L43-L47 | train |
activescaffold/active_scaffold | lib/active_scaffold/data_structures/action_links.rb | ActiveScaffold::DataStructures.ActionLinks.[] | def [](val)
links = []
@set.each do |item|
if item.is_a?(ActiveScaffold::DataStructures::ActionLinks)
collected = item[val]
links << collected unless collected.nil?
elsif item.action.to_s == val.to_s
links << item
end
end
links.first
end | ruby | def [](val)
links = []
@set.each do |item|
if item.is_a?(ActiveScaffold::DataStructures::ActionLinks)
collected = item[val]
links << collected unless collected.nil?
elsif item.action.to_s == val.to_s
links << item
end
end
links.first
end | [
"def",
"[]",
"(",
"val",
")",
"links",
"=",
"[",
"]",
"@set",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"is_a?",
"(",
"ActiveScaffold",
"::",
"DataStructures",
"::",
"ActionLinks",
")",
"collected",
"=",
"item",
"[",
"val",
"]",
"links",
"<<",
"collected",
"unless",
"collected",
".",
"nil?",
"elsif",
"item",
".",
"action",
".",
"to_s",
"==",
"val",
".",
"to_s",
"links",
"<<",
"item",
"end",
"end",
"links",
".",
"first",
"end"
] | finds an ActionLink by matching the action | [
"finds",
"an",
"ActionLink",
"by",
"matching",
"the",
"action"
] | 1954f85b5395d09de09fa86f3ea70c29bbee2612 | https://github.com/activescaffold/active_scaffold/blob/1954f85b5395d09de09fa86f3ea70c29bbee2612/lib/active_scaffold/data_structures/action_links.rb#L50-L61 | train |
activescaffold/active_scaffold | lib/active_scaffold/data_structures/action_links.rb | ActiveScaffold::DataStructures.ActionLinks.each | def each(options = {}, &block)
method = options[:reverse] ? :reverse_each : :each
@set.sort_by(&:weight).send(method) do |item|
if item.is_a?(ActiveScaffold::DataStructures::ActionLinks) && !options[:groups]
item.each(options, &block)
elsif options[:include_set]
yield item, @set
else
yield item
end
end
end | ruby | def each(options = {}, &block)
method = options[:reverse] ? :reverse_each : :each
@set.sort_by(&:weight).send(method) do |item|
if item.is_a?(ActiveScaffold::DataStructures::ActionLinks) && !options[:groups]
item.each(options, &block)
elsif options[:include_set]
yield item, @set
else
yield item
end
end
end | [
"def",
"each",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"method",
"=",
"options",
"[",
":reverse",
"]",
"?",
":reverse_each",
":",
":each",
"@set",
".",
"sort_by",
"(",
":weight",
")",
".",
"send",
"(",
"method",
")",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"is_a?",
"(",
"ActiveScaffold",
"::",
"DataStructures",
"::",
"ActionLinks",
")",
"&&",
"!",
"options",
"[",
":groups",
"]",
"item",
".",
"each",
"(",
"options",
",",
"block",
")",
"elsif",
"options",
"[",
":include_set",
"]",
"yield",
"item",
",",
"@set",
"else",
"yield",
"item",
"end",
"end",
"end"
] | iterates over the links, possibly by type | [
"iterates",
"over",
"the",
"links",
"possibly",
"by",
"type"
] | 1954f85b5395d09de09fa86f3ea70c29bbee2612 | https://github.com/activescaffold/active_scaffold/blob/1954f85b5395d09de09fa86f3ea70c29bbee2612/lib/active_scaffold/data_structures/action_links.rb#L98-L109 | train |
activescaffold/active_scaffold | lib/active_scaffold/data_structures/action_columns.rb | ActiveScaffold::DataStructures.ActionColumns.add_subgroup | def add_subgroup(label, &proc)
columns = ActiveScaffold::DataStructures::ActionColumns.new
columns.label = label
columns.action = action
columns.configure(&proc)
exclude columns.collect_columns
add columns
end | ruby | def add_subgroup(label, &proc)
columns = ActiveScaffold::DataStructures::ActionColumns.new
columns.label = label
columns.action = action
columns.configure(&proc)
exclude columns.collect_columns
add columns
end | [
"def",
"add_subgroup",
"(",
"label",
",",
"&",
"proc",
")",
"columns",
"=",
"ActiveScaffold",
"::",
"DataStructures",
"::",
"ActionColumns",
".",
"new",
"columns",
".",
"label",
"=",
"label",
"columns",
".",
"action",
"=",
"action",
"columns",
".",
"configure",
"(",
"proc",
")",
"exclude",
"columns",
".",
"collect_columns",
"add",
"columns",
"end"
] | nests a subgroup in the column set | [
"nests",
"a",
"subgroup",
"in",
"the",
"column",
"set"
] | 1954f85b5395d09de09fa86f3ea70c29bbee2612 | https://github.com/activescaffold/active_scaffold/blob/1954f85b5395d09de09fa86f3ea70c29bbee2612/lib/active_scaffold/data_structures/action_columns.rb#L38-L45 | train |
activescaffold/active_scaffold | lib/active_scaffold/actions/delete.rb | ActiveScaffold::Actions.Delete.do_destroy | def do_destroy(record)
record ||= destroy_find_record
begin
self.successful = record.destroy
rescue StandardError => exception
flash[:warning] = as_(:cant_destroy_record, :record => ERB::Util.h(record.to_label))
self.successful = false
logger.warn do
"\n\n#{exception.class} (#{exception.message}):\n " +
Rails.backtrace_cleaner.clean(exception.backtrace).join("\n ") +
"\n\n"
end
end
end | ruby | def do_destroy(record)
record ||= destroy_find_record
begin
self.successful = record.destroy
rescue StandardError => exception
flash[:warning] = as_(:cant_destroy_record, :record => ERB::Util.h(record.to_label))
self.successful = false
logger.warn do
"\n\n#{exception.class} (#{exception.message}):\n " +
Rails.backtrace_cleaner.clean(exception.backtrace).join("\n ") +
"\n\n"
end
end
end | [
"def",
"do_destroy",
"(",
"record",
")",
"record",
"||=",
"destroy_find_record",
"begin",
"self",
".",
"successful",
"=",
"record",
".",
"destroy",
"rescue",
"StandardError",
"=>",
"exception",
"flash",
"[",
":warning",
"]",
"=",
"as_",
"(",
":cant_destroy_record",
",",
":record",
"=>",
"ERB",
"::",
"Util",
".",
"h",
"(",
"record",
".",
"to_label",
")",
")",
"self",
".",
"successful",
"=",
"false",
"logger",
".",
"warn",
"do",
"\"\\n\\n#{exception.class} (#{exception.message}):\\n \"",
"+",
"Rails",
".",
"backtrace_cleaner",
".",
"clean",
"(",
"exception",
".",
"backtrace",
")",
".",
"join",
"(",
"\"\\n \"",
")",
"+",
"\"\\n\\n\"",
"end",
"end",
"end"
] | A simple method to handle the actual destroying of a record
May be overridden to customize the behavior | [
"A",
"simple",
"method",
"to",
"handle",
"the",
"actual",
"destroying",
"of",
"a",
"record",
"May",
"be",
"overridden",
"to",
"customize",
"the",
"behavior"
] | 1954f85b5395d09de09fa86f3ea70c29bbee2612 | https://github.com/activescaffold/active_scaffold/blob/1954f85b5395d09de09fa86f3ea70c29bbee2612/lib/active_scaffold/actions/delete.rb#L40-L53 | train |
activescaffold/active_scaffold | lib/active_scaffold/constraints.rb | ActiveScaffold.Constraints.conditions_from_constraints | def conditions_from_constraints
hash_conditions = {}
conditions = [hash_conditions]
active_scaffold_constraints.each do |k, v|
column = active_scaffold_config.columns[k]
if column
# Assume this is a multi-level association constraint.
# example:
# data model: Park -> Den -> Bear
# constraint: :den => {:park => 5}
if params_hash? v
far_association = column.association.klass.reflect_on_association(v.keys.first)
field = far_association.klass.primary_key
table = far_association.table_name
active_scaffold_references.concat([{k => far_association.name}]) # e.g. {:den => :park}
hash_conditions.deep_merge!(table => {field => v.values.first})
# association column constraint
elsif column.association
join_from_association_constraint(column)
hash_conditions.deep_merge!(condition_from_association_constraint(column.association, v))
# regular column constraints
elsif column.searchable? && params[column.name] != v
active_scaffold_references.concat column.references if column.includes.present?
conditions << [column.search_sql.collect { |search_sql| "#{search_sql} = ?" }.join(' OR '), *([v] * column.search_sql.size)]
end
# unknown-to-activescaffold-but-real-database-column constraint
elsif active_scaffold_config.model.columns_hash[k.to_s] && params[column.name] != v
hash_conditions.deep_merge!(k => v)
else
raise ActiveScaffold::MalformedConstraint, constraint_error(active_scaffold_config.model, k), caller
end
end
conditions.reject(&:blank?)
end | ruby | def conditions_from_constraints
hash_conditions = {}
conditions = [hash_conditions]
active_scaffold_constraints.each do |k, v|
column = active_scaffold_config.columns[k]
if column
# Assume this is a multi-level association constraint.
# example:
# data model: Park -> Den -> Bear
# constraint: :den => {:park => 5}
if params_hash? v
far_association = column.association.klass.reflect_on_association(v.keys.first)
field = far_association.klass.primary_key
table = far_association.table_name
active_scaffold_references.concat([{k => far_association.name}]) # e.g. {:den => :park}
hash_conditions.deep_merge!(table => {field => v.values.first})
# association column constraint
elsif column.association
join_from_association_constraint(column)
hash_conditions.deep_merge!(condition_from_association_constraint(column.association, v))
# regular column constraints
elsif column.searchable? && params[column.name] != v
active_scaffold_references.concat column.references if column.includes.present?
conditions << [column.search_sql.collect { |search_sql| "#{search_sql} = ?" }.join(' OR '), *([v] * column.search_sql.size)]
end
# unknown-to-activescaffold-but-real-database-column constraint
elsif active_scaffold_config.model.columns_hash[k.to_s] && params[column.name] != v
hash_conditions.deep_merge!(k => v)
else
raise ActiveScaffold::MalformedConstraint, constraint_error(active_scaffold_config.model, k), caller
end
end
conditions.reject(&:blank?)
end | [
"def",
"conditions_from_constraints",
"hash_conditions",
"=",
"{",
"}",
"conditions",
"=",
"[",
"hash_conditions",
"]",
"active_scaffold_constraints",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"column",
"=",
"active_scaffold_config",
".",
"columns",
"[",
"k",
"]",
"if",
"column",
"# Assume this is a multi-level association constraint.",
"# example:",
"# data model: Park -> Den -> Bear",
"# constraint: :den => {:park => 5}",
"if",
"params_hash?",
"v",
"far_association",
"=",
"column",
".",
"association",
".",
"klass",
".",
"reflect_on_association",
"(",
"v",
".",
"keys",
".",
"first",
")",
"field",
"=",
"far_association",
".",
"klass",
".",
"primary_key",
"table",
"=",
"far_association",
".",
"table_name",
"active_scaffold_references",
".",
"concat",
"(",
"[",
"{",
"k",
"=>",
"far_association",
".",
"name",
"}",
"]",
")",
"# e.g. {:den => :park}",
"hash_conditions",
".",
"deep_merge!",
"(",
"table",
"=>",
"{",
"field",
"=>",
"v",
".",
"values",
".",
"first",
"}",
")",
"# association column constraint",
"elsif",
"column",
".",
"association",
"join_from_association_constraint",
"(",
"column",
")",
"hash_conditions",
".",
"deep_merge!",
"(",
"condition_from_association_constraint",
"(",
"column",
".",
"association",
",",
"v",
")",
")",
"# regular column constraints",
"elsif",
"column",
".",
"searchable?",
"&&",
"params",
"[",
"column",
".",
"name",
"]",
"!=",
"v",
"active_scaffold_references",
".",
"concat",
"column",
".",
"references",
"if",
"column",
".",
"includes",
".",
"present?",
"conditions",
"<<",
"[",
"column",
".",
"search_sql",
".",
"collect",
"{",
"|",
"search_sql",
"|",
"\"#{search_sql} = ?\"",
"}",
".",
"join",
"(",
"' OR '",
")",
",",
"(",
"[",
"v",
"]",
"*",
"column",
".",
"search_sql",
".",
"size",
")",
"]",
"end",
"# unknown-to-activescaffold-but-real-database-column constraint",
"elsif",
"active_scaffold_config",
".",
"model",
".",
"columns_hash",
"[",
"k",
".",
"to_s",
"]",
"&&",
"params",
"[",
"column",
".",
"name",
"]",
"!=",
"v",
"hash_conditions",
".",
"deep_merge!",
"(",
"k",
"=>",
"v",
")",
"else",
"raise",
"ActiveScaffold",
"::",
"MalformedConstraint",
",",
"constraint_error",
"(",
"active_scaffold_config",
".",
"model",
",",
"k",
")",
",",
"caller",
"end",
"end",
"conditions",
".",
"reject",
"(",
":blank?",
")",
"end"
] | Returns search conditions based on the current scaffold constraints.
Supports constraints based on either a column name (in which case it checks for an association
or just uses the search_sql) or a database field name.
All of this work is primarily to support nested scaffolds in a manner generally useful for other
embedded scaffolds. | [
"Returns",
"search",
"conditions",
"based",
"on",
"the",
"current",
"scaffold",
"constraints",
"."
] | 1954f85b5395d09de09fa86f3ea70c29bbee2612 | https://github.com/activescaffold/active_scaffold/blob/1954f85b5395d09de09fa86f3ea70c29bbee2612/lib/active_scaffold/constraints.rb#L44-L80 | train |
activescaffold/active_scaffold | lib/active_scaffold/constraints.rb | ActiveScaffold.Constraints.condition_from_association_constraint | def condition_from_association_constraint(association, value)
# when the reverse association is a :belongs_to, the id for the associated object only exists as
# the primary_key on the other table. so for :has_one and :has_many (when the reverse is :belongs_to),
# we have to use the other model's primary_key.
#
# please see the relevant tests for concrete examples.
field =
if association.belongs_to?
association.foreign_key
else
association.klass.primary_key
end
table = association.belongs_to? ? active_scaffold_config.model.table_name : association.table_name
value = association.klass.find(value).send(association.primary_key) if association.primary_key
if association.polymorphic?
unless value.is_a?(Array) && value.size == 2
raise ActiveScaffold::MalformedConstraint, polymorphic_constraint_error(association), caller
end
condition = {table => {association.foreign_type => value[0], field => value[1]}}
else
condition = {table => {field.to_s => value}}
end
condition
end | ruby | def condition_from_association_constraint(association, value)
# when the reverse association is a :belongs_to, the id for the associated object only exists as
# the primary_key on the other table. so for :has_one and :has_many (when the reverse is :belongs_to),
# we have to use the other model's primary_key.
#
# please see the relevant tests for concrete examples.
field =
if association.belongs_to?
association.foreign_key
else
association.klass.primary_key
end
table = association.belongs_to? ? active_scaffold_config.model.table_name : association.table_name
value = association.klass.find(value).send(association.primary_key) if association.primary_key
if association.polymorphic?
unless value.is_a?(Array) && value.size == 2
raise ActiveScaffold::MalformedConstraint, polymorphic_constraint_error(association), caller
end
condition = {table => {association.foreign_type => value[0], field => value[1]}}
else
condition = {table => {field.to_s => value}}
end
condition
end | [
"def",
"condition_from_association_constraint",
"(",
"association",
",",
"value",
")",
"# when the reverse association is a :belongs_to, the id for the associated object only exists as",
"# the primary_key on the other table. so for :has_one and :has_many (when the reverse is :belongs_to),",
"# we have to use the other model's primary_key.",
"#",
"# please see the relevant tests for concrete examples.",
"field",
"=",
"if",
"association",
".",
"belongs_to?",
"association",
".",
"foreign_key",
"else",
"association",
".",
"klass",
".",
"primary_key",
"end",
"table",
"=",
"association",
".",
"belongs_to?",
"?",
"active_scaffold_config",
".",
"model",
".",
"table_name",
":",
"association",
".",
"table_name",
"value",
"=",
"association",
".",
"klass",
".",
"find",
"(",
"value",
")",
".",
"send",
"(",
"association",
".",
"primary_key",
")",
"if",
"association",
".",
"primary_key",
"if",
"association",
".",
"polymorphic?",
"unless",
"value",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"value",
".",
"size",
"==",
"2",
"raise",
"ActiveScaffold",
"::",
"MalformedConstraint",
",",
"polymorphic_constraint_error",
"(",
"association",
")",
",",
"caller",
"end",
"condition",
"=",
"{",
"table",
"=>",
"{",
"association",
".",
"foreign_type",
"=>",
"value",
"[",
"0",
"]",
",",
"field",
"=>",
"value",
"[",
"1",
"]",
"}",
"}",
"else",
"condition",
"=",
"{",
"table",
"=>",
"{",
"field",
".",
"to_s",
"=>",
"value",
"}",
"}",
"end",
"condition",
"end"
] | We do NOT want to use .search_sql. If anything, search_sql will refer
to a human-searchable value on the associated record. | [
"We",
"do",
"NOT",
"want",
"to",
"use",
".",
"search_sql",
".",
"If",
"anything",
"search_sql",
"will",
"refer",
"to",
"a",
"human",
"-",
"searchable",
"value",
"on",
"the",
"associated",
"record",
"."
] | 1954f85b5395d09de09fa86f3ea70c29bbee2612 | https://github.com/activescaffold/active_scaffold/blob/1954f85b5395d09de09fa86f3ea70c29bbee2612/lib/active_scaffold/constraints.rb#L96-L123 | train |
activescaffold/active_scaffold | lib/active_scaffold/constraints.rb | ActiveScaffold.Constraints.apply_constraints_to_record | def apply_constraints_to_record(record, options = {})
options[:allow_autosave] = false if options[:allow_autosave].nil?
constraints = options[:constraints] || active_scaffold_constraints
config = record.is_a?(active_scaffold_config.model) ? active_scaffold_config : active_scaffold_config_for(record.class)
constraints.each do |k, v|
column = config.columns[k]
if column&.association
if column.association.collection?
record.send(k.to_s).send(:<<, column.association.klass.find(v))
elsif column.association.polymorphic?
unless v.is_a?(Array) && v.size == 2
raise ActiveScaffold::MalformedConstraint, polymorphic_constraint_error(column.association), caller
end
record.send("#{k}=", v[0].constantize.find(v[1]))
else # regular singular association
record.send("#{k}=", column.association.klass.find(v))
# setting the belongs_to side of a has_one isn't safe. if the has_one was already
# specified, rails won't automatically clear out the previous associated record.
#
# note that we can't take the extra step to correct this unless we're permitted to
# run operations where activerecord auto-saves the object.
reverse = column.association.reverse_association
if reverse.singular? && !reverse.belongs_to? && options[:allow_autosave]
record.send(k).send("#{reverse.name}=", record)
end
end
else
record.send("#{k}=", v)
end
end
end | ruby | def apply_constraints_to_record(record, options = {})
options[:allow_autosave] = false if options[:allow_autosave].nil?
constraints = options[:constraints] || active_scaffold_constraints
config = record.is_a?(active_scaffold_config.model) ? active_scaffold_config : active_scaffold_config_for(record.class)
constraints.each do |k, v|
column = config.columns[k]
if column&.association
if column.association.collection?
record.send(k.to_s).send(:<<, column.association.klass.find(v))
elsif column.association.polymorphic?
unless v.is_a?(Array) && v.size == 2
raise ActiveScaffold::MalformedConstraint, polymorphic_constraint_error(column.association), caller
end
record.send("#{k}=", v[0].constantize.find(v[1]))
else # regular singular association
record.send("#{k}=", column.association.klass.find(v))
# setting the belongs_to side of a has_one isn't safe. if the has_one was already
# specified, rails won't automatically clear out the previous associated record.
#
# note that we can't take the extra step to correct this unless we're permitted to
# run operations where activerecord auto-saves the object.
reverse = column.association.reverse_association
if reverse.singular? && !reverse.belongs_to? && options[:allow_autosave]
record.send(k).send("#{reverse.name}=", record)
end
end
else
record.send("#{k}=", v)
end
end
end | [
"def",
"apply_constraints_to_record",
"(",
"record",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":allow_autosave",
"]",
"=",
"false",
"if",
"options",
"[",
":allow_autosave",
"]",
".",
"nil?",
"constraints",
"=",
"options",
"[",
":constraints",
"]",
"||",
"active_scaffold_constraints",
"config",
"=",
"record",
".",
"is_a?",
"(",
"active_scaffold_config",
".",
"model",
")",
"?",
"active_scaffold_config",
":",
"active_scaffold_config_for",
"(",
"record",
".",
"class",
")",
"constraints",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"column",
"=",
"config",
".",
"columns",
"[",
"k",
"]",
"if",
"column",
"&.",
"association",
"if",
"column",
".",
"association",
".",
"collection?",
"record",
".",
"send",
"(",
"k",
".",
"to_s",
")",
".",
"send",
"(",
":<<",
",",
"column",
".",
"association",
".",
"klass",
".",
"find",
"(",
"v",
")",
")",
"elsif",
"column",
".",
"association",
".",
"polymorphic?",
"unless",
"v",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"v",
".",
"size",
"==",
"2",
"raise",
"ActiveScaffold",
"::",
"MalformedConstraint",
",",
"polymorphic_constraint_error",
"(",
"column",
".",
"association",
")",
",",
"caller",
"end",
"record",
".",
"send",
"(",
"\"#{k}=\"",
",",
"v",
"[",
"0",
"]",
".",
"constantize",
".",
"find",
"(",
"v",
"[",
"1",
"]",
")",
")",
"else",
"# regular singular association",
"record",
".",
"send",
"(",
"\"#{k}=\"",
",",
"column",
".",
"association",
".",
"klass",
".",
"find",
"(",
"v",
")",
")",
"# setting the belongs_to side of a has_one isn't safe. if the has_one was already",
"# specified, rails won't automatically clear out the previous associated record.",
"#",
"# note that we can't take the extra step to correct this unless we're permitted to",
"# run operations where activerecord auto-saves the object.",
"reverse",
"=",
"column",
".",
"association",
".",
"reverse_association",
"if",
"reverse",
".",
"singular?",
"&&",
"!",
"reverse",
".",
"belongs_to?",
"&&",
"options",
"[",
":allow_autosave",
"]",
"record",
".",
"send",
"(",
"k",
")",
".",
"send",
"(",
"\"#{reverse.name}=\"",
",",
"record",
")",
"end",
"end",
"else",
"record",
".",
"send",
"(",
"\"#{k}=\"",
",",
"v",
")",
"end",
"end",
"end"
] | Applies constraints to the given record.
Searches through the known columns for association columns. If the given constraint is an association,
it assumes that the constraint value is an id. It then does a association.klass.find with the value
and adds the associated object to the record.
For some operations ActiveRecord will automatically update the database. That's not always ok.
If it *is* ok (e.g. you're in a transaction), then set :allow_autosave to true. | [
"Applies",
"constraints",
"to",
"the",
"given",
"record",
"."
] | 1954f85b5395d09de09fa86f3ea70c29bbee2612 | https://github.com/activescaffold/active_scaffold/blob/1954f85b5395d09de09fa86f3ea70c29bbee2612/lib/active_scaffold/constraints.rb#L141-L173 | train |
rossta/montrose | lib/montrose/schedule.rb | Montrose.Schedule.events | def events(opts = {})
enums = @rules.map { |r| r.merge(opts).events }
Enumerator.new do |y|
loop do
enum = active_enums(enums).min_by(&:peek) or break
y << enum.next
end
end
end | ruby | def events(opts = {})
enums = @rules.map { |r| r.merge(opts).events }
Enumerator.new do |y|
loop do
enum = active_enums(enums).min_by(&:peek) or break
y << enum.next
end
end
end | [
"def",
"events",
"(",
"opts",
"=",
"{",
"}",
")",
"enums",
"=",
"@rules",
".",
"map",
"{",
"|",
"r",
"|",
"r",
".",
"merge",
"(",
"opts",
")",
".",
"events",
"}",
"Enumerator",
".",
"new",
"do",
"|",
"y",
"|",
"loop",
"do",
"enum",
"=",
"active_enums",
"(",
"enums",
")",
".",
"min_by",
"(",
":peek",
")",
"or",
"break",
"y",
"<<",
"enum",
".",
"next",
"end",
"end",
"end"
] | Returns an enumerator for iterating over timestamps in the schedule
@example Return the events
schedule = Montrose::Schedule.build do |s|
s << { every: :day }
end
schedule.events
@return [Enumerator] an enumerator of recurrence timestamps | [
"Returns",
"an",
"enumerator",
"for",
"iterating",
"over",
"timestamps",
"in",
"the",
"schedule"
] | 91af7d2d5c337aa255510179d24eb023775674bb | https://github.com/rossta/montrose/blob/91af7d2d5c337aa255510179d24eb023775674bb/lib/montrose/schedule.rb#L72-L80 | train |
rossta/montrose | lib/montrose/stack.rb | Montrose.Stack.advance | def advance(time)
yes, no = @stack.partition { |rule| rule.include?(time) }
if no.empty?
yes.all? { |rule| rule.advance!(time) } or return false
puts time if ENV["DEBUG"]
yield time if block_given?
true
else
no.any? { |rule| rule.continue?(time) }
end
end | ruby | def advance(time)
yes, no = @stack.partition { |rule| rule.include?(time) }
if no.empty?
yes.all? { |rule| rule.advance!(time) } or return false
puts time if ENV["DEBUG"]
yield time if block_given?
true
else
no.any? { |rule| rule.continue?(time) }
end
end | [
"def",
"advance",
"(",
"time",
")",
"yes",
",",
"no",
"=",
"@stack",
".",
"partition",
"{",
"|",
"rule",
"|",
"rule",
".",
"include?",
"(",
"time",
")",
"}",
"if",
"no",
".",
"empty?",
"yes",
".",
"all?",
"{",
"|",
"rule",
"|",
"rule",
".",
"advance!",
"(",
"time",
")",
"}",
"or",
"return",
"false",
"puts",
"time",
"if",
"ENV",
"[",
"\"DEBUG\"",
"]",
"yield",
"time",
"if",
"block_given?",
"true",
"else",
"no",
".",
"any?",
"{",
"|",
"rule",
"|",
"rule",
".",
"continue?",
"(",
"time",
")",
"}",
"end",
"end"
] | Given a time instance, advances state of when all
recurrence rules on the stack match, and yielding
time to the block, otherwise, invokes break? on
non-matching rules.
@param [Time] time - time instance candidate for recurrence | [
"Given",
"a",
"time",
"instance",
"advances",
"state",
"of",
"when",
"all",
"recurrence",
"rules",
"on",
"the",
"stack",
"match",
"and",
"yielding",
"time",
"to",
"the",
"block",
"otherwise",
"invokes",
"break?",
"on",
"non",
"-",
"matching",
"rules",
"."
] | 91af7d2d5c337aa255510179d24eb023775674bb | https://github.com/rossta/montrose/blob/91af7d2d5c337aa255510179d24eb023775674bb/lib/montrose/stack.rb#L42-L53 | train |
mailgun/mailgun-ruby | lib/mailgun/messages/message_builder.rb | Mailgun.MessageBuilder.add_campaign_id | def add_campaign_id(campaign_id)
fail(Mailgun::ParameterError, 'Too many campaigns added to message.', campaign_id) if @counters[:attributes][:campaign_id] >= Mailgun::Chains::MAX_CAMPAIGN_IDS
set_multi_complex('o:campaign', campaign_id)
@counters[:attributes][:campaign_id] += 1
end | ruby | def add_campaign_id(campaign_id)
fail(Mailgun::ParameterError, 'Too many campaigns added to message.', campaign_id) if @counters[:attributes][:campaign_id] >= Mailgun::Chains::MAX_CAMPAIGN_IDS
set_multi_complex('o:campaign', campaign_id)
@counters[:attributes][:campaign_id] += 1
end | [
"def",
"add_campaign_id",
"(",
"campaign_id",
")",
"fail",
"(",
"Mailgun",
"::",
"ParameterError",
",",
"'Too many campaigns added to message.'",
",",
"campaign_id",
")",
"if",
"@counters",
"[",
":attributes",
"]",
"[",
":campaign_id",
"]",
">=",
"Mailgun",
"::",
"Chains",
"::",
"MAX_CAMPAIGN_IDS",
"set_multi_complex",
"(",
"'o:campaign'",
",",
"campaign_id",
")",
"@counters",
"[",
":attributes",
"]",
"[",
":campaign_id",
"]",
"+=",
"1",
"end"
] | Add campaign IDs to message. Limit of 3 per message.
@param [String] campaign_id A defined campaign ID to add to the message.
@return [void] | [
"Add",
"campaign",
"IDs",
"to",
"message",
".",
"Limit",
"of",
"3",
"per",
"message",
"."
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/messages/message_builder.rb#L176-L181 | train |
mailgun/mailgun-ruby | lib/mailgun/messages/message_builder.rb | Mailgun.MessageBuilder.add_tag | def add_tag(tag)
if @counters[:attributes][:tag] >= Mailgun::Chains::MAX_TAGS
fail Mailgun::ParameterError, 'Too many tags added to message.', tag
end
set_multi_complex('o:tag', tag)
@counters[:attributes][:tag] += 1
end | ruby | def add_tag(tag)
if @counters[:attributes][:tag] >= Mailgun::Chains::MAX_TAGS
fail Mailgun::ParameterError, 'Too many tags added to message.', tag
end
set_multi_complex('o:tag', tag)
@counters[:attributes][:tag] += 1
end | [
"def",
"add_tag",
"(",
"tag",
")",
"if",
"@counters",
"[",
":attributes",
"]",
"[",
":tag",
"]",
">=",
"Mailgun",
"::",
"Chains",
"::",
"MAX_TAGS",
"fail",
"Mailgun",
"::",
"ParameterError",
",",
"'Too many tags added to message.'",
",",
"tag",
"end",
"set_multi_complex",
"(",
"'o:tag'",
",",
"tag",
")",
"@counters",
"[",
":attributes",
"]",
"[",
":tag",
"]",
"+=",
"1",
"end"
] | Add tags to message. Limit of 3 per message.
@param [String] tag A defined campaign ID to add to the message.
@return [void] | [
"Add",
"tags",
"to",
"message",
".",
"Limit",
"of",
"3",
"per",
"message",
"."
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/messages/message_builder.rb#L187-L193 | train |
mailgun/mailgun-ruby | lib/mailgun/messages/message_builder.rb | Mailgun.MessageBuilder.header | def header(name, data)
fail(Mailgun::ParameterError, 'Header name for message must be specified') if name.to_s.empty?
begin
jsondata = make_json data
set_single("h:#{name}", jsondata)
rescue Mailgun::ParameterError
set_single("h:#{name}", data)
end
end | ruby | def header(name, data)
fail(Mailgun::ParameterError, 'Header name for message must be specified') if name.to_s.empty?
begin
jsondata = make_json data
set_single("h:#{name}", jsondata)
rescue Mailgun::ParameterError
set_single("h:#{name}", data)
end
end | [
"def",
"header",
"(",
"name",
",",
"data",
")",
"fail",
"(",
"Mailgun",
"::",
"ParameterError",
",",
"'Header name for message must be specified'",
")",
"if",
"name",
".",
"to_s",
".",
"empty?",
"begin",
"jsondata",
"=",
"make_json",
"data",
"set_single",
"(",
"\"h:#{name}\"",
",",
"jsondata",
")",
"rescue",
"Mailgun",
"::",
"ParameterError",
"set_single",
"(",
"\"h:#{name}\"",
",",
"data",
")",
"end",
"end"
] | Add custom data to the message. The data should be either a hash or JSON
encoded. The custom data will be added as a header to your message.
@param [string] name A name for the custom data. (Ex. X-Mailgun-<Name of Data>: {})
@param [Hash] data Either a hash or JSON string.
@return [void] | [
"Add",
"custom",
"data",
"to",
"the",
"message",
".",
"The",
"data",
"should",
"be",
"either",
"a",
"hash",
"or",
"JSON",
"encoded",
".",
"The",
"custom",
"data",
"will",
"be",
"added",
"as",
"a",
"header",
"to",
"your",
"message",
"."
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/messages/message_builder.rb#L247-L255 | train |
mailgun/mailgun-ruby | lib/mailgun/messages/message_builder.rb | Mailgun.MessageBuilder.bool_lookup | def bool_lookup(value)
return 'yes' if %w(true yes yep).include? value.to_s.downcase
return 'no' if %w(false no nope).include? value.to_s.downcase
value
end | ruby | def bool_lookup(value)
return 'yes' if %w(true yes yep).include? value.to_s.downcase
return 'no' if %w(false no nope).include? value.to_s.downcase
value
end | [
"def",
"bool_lookup",
"(",
"value",
")",
"return",
"'yes'",
"if",
"%w(",
"true",
"yes",
"yep",
")",
".",
"include?",
"value",
".",
"to_s",
".",
"downcase",
"return",
"'no'",
"if",
"%w(",
"false",
"no",
"nope",
")",
".",
"include?",
"value",
".",
"to_s",
".",
"downcase",
"value",
"end"
] | Converts boolean type to string
@param [String] value The item to convert
@return [void] | [
"Converts",
"boolean",
"type",
"to",
"string"
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/messages/message_builder.rb#L342-L346 | train |
mailgun/mailgun-ruby | lib/mailgun/messages/batch_message.rb | Mailgun.BatchMessage.send_message | def send_message
rkey = 'recipient-variables'
set_multi_simple rkey, JSON.generate(@recipient_variables)
@message[rkey] = @message[rkey].first if @message.key?(rkey)
response = @client.send_message(@domain, @message).to_h!
message_id = response['id'].gsub(/\>|\</, '')
@message_ids[message_id] = count_recipients
reset_message
end | ruby | def send_message
rkey = 'recipient-variables'
set_multi_simple rkey, JSON.generate(@recipient_variables)
@message[rkey] = @message[rkey].first if @message.key?(rkey)
response = @client.send_message(@domain, @message).to_h!
message_id = response['id'].gsub(/\>|\</, '')
@message_ids[message_id] = count_recipients
reset_message
end | [
"def",
"send_message",
"rkey",
"=",
"'recipient-variables'",
"set_multi_simple",
"rkey",
",",
"JSON",
".",
"generate",
"(",
"@recipient_variables",
")",
"@message",
"[",
"rkey",
"]",
"=",
"@message",
"[",
"rkey",
"]",
".",
"first",
"if",
"@message",
".",
"key?",
"(",
"rkey",
")",
"response",
"=",
"@client",
".",
"send_message",
"(",
"@domain",
",",
"@message",
")",
".",
"to_h!",
"message_id",
"=",
"response",
"[",
"'id'",
"]",
".",
"gsub",
"(",
"/",
"\\>",
"\\<",
"/",
",",
"''",
")",
"@message_ids",
"[",
"message_id",
"]",
"=",
"count_recipients",
"reset_message",
"end"
] | This method initiates a batch send to the API. It formats the recipient
variables, posts to the API, gathers the message IDs, then flushes that data
to prepare for the next batch. This method implements the Mailgun Client, thus,
an exception will be thrown if a communication error occurs.
@return [Boolean] | [
"This",
"method",
"initiates",
"a",
"batch",
"send",
"to",
"the",
"API",
".",
"It",
"formats",
"the",
"recipient",
"variables",
"posts",
"to",
"the",
"API",
"gathers",
"the",
"message",
"IDs",
"then",
"flushes",
"that",
"data",
"to",
"prepare",
"for",
"the",
"next",
"batch",
".",
"This",
"method",
"implements",
"the",
"Mailgun",
"Client",
"thus",
"an",
"exception",
"will",
"be",
"thrown",
"if",
"a",
"communication",
"error",
"occurs",
"."
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/messages/batch_message.rb#L85-L94 | train |
mailgun/mailgun-ruby | lib/mailgun/messages/batch_message.rb | Mailgun.BatchMessage.store_recipient_variables | def store_recipient_variables(recipient_type, address, variables)
variables = { id: @counters[:recipients][recipient_type] } unless variables
@recipient_variables[address] = variables
end | ruby | def store_recipient_variables(recipient_type, address, variables)
variables = { id: @counters[:recipients][recipient_type] } unless variables
@recipient_variables[address] = variables
end | [
"def",
"store_recipient_variables",
"(",
"recipient_type",
",",
"address",
",",
"variables",
")",
"variables",
"=",
"{",
"id",
":",
"@counters",
"[",
":recipients",
"]",
"[",
"recipient_type",
"]",
"}",
"unless",
"variables",
"@recipient_variables",
"[",
"address",
"]",
"=",
"variables",
"end"
] | This method stores recipient variables for each recipient added, if
variables exist. | [
"This",
"method",
"stores",
"recipient",
"variables",
"for",
"each",
"recipient",
"added",
"if",
"variables",
"exist",
"."
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/messages/batch_message.rb#L98-L101 | train |
mailgun/mailgun-ruby | lib/mailgun/response.rb | Mailgun.Response.to_yaml | def to_yaml
YAML.dump(to_h)
rescue => err
raise ParseError.new(err), err
end | ruby | def to_yaml
YAML.dump(to_h)
rescue => err
raise ParseError.new(err), err
end | [
"def",
"to_yaml",
"YAML",
".",
"dump",
"(",
"to_h",
")",
"rescue",
"=>",
"err",
"raise",
"ParseError",
".",
"new",
"(",
"err",
")",
",",
"err",
"end"
] | Return response as Yaml
@return [String] A string containing response as YAML | [
"Return",
"response",
"as",
"Yaml"
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/response.rb#L47-L51 | train |
mailgun/mailgun-ruby | lib/railgun/mailer.rb | Railgun.Mailer.deliver! | def deliver!(mail)
mg_message = Railgun.transform_for_mailgun(mail)
response = @mg_client.send_message(@domain, mg_message)
if response.code == 200 then
mg_id = response.to_h['id']
mail.message_id = mg_id
end
response
end | ruby | def deliver!(mail)
mg_message = Railgun.transform_for_mailgun(mail)
response = @mg_client.send_message(@domain, mg_message)
if response.code == 200 then
mg_id = response.to_h['id']
mail.message_id = mg_id
end
response
end | [
"def",
"deliver!",
"(",
"mail",
")",
"mg_message",
"=",
"Railgun",
".",
"transform_for_mailgun",
"(",
"mail",
")",
"response",
"=",
"@mg_client",
".",
"send_message",
"(",
"@domain",
",",
"mg_message",
")",
"if",
"response",
".",
"code",
"==",
"200",
"then",
"mg_id",
"=",
"response",
".",
"to_h",
"[",
"'id'",
"]",
"mail",
".",
"message_id",
"=",
"mg_id",
"end",
"response",
"end"
] | Initialize the Railgun mailer.
@param [Hash] config Hash of config values, typically from `app_config.action_mailer.mailgun_config` | [
"Initialize",
"the",
"Railgun",
"mailer",
"."
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/railgun/mailer.rb#L42-L51 | train |
mailgun/mailgun-ruby | lib/mailgun/client.rb | Mailgun.Client.send_message | def send_message(working_domain, data)
if test_mode? then
Mailgun::Client.deliveries << data
return Response.from_hash(
{
:body => '{"id": "test-mode-mail@localhost", "message": "Queued. Thank you."}',
:code => 200,
}
)
end
case data
when Hash
# Remove nil values from the data hash
# Submitting nils to the API will likely cause an error.
# See also: https://github.com/mailgun/mailgun-ruby/issues/32
data = data.select { |k, v| v != nil }
if data.key?(:message)
if data[:message].is_a?(String)
data[:message] = convert_string_to_file(data[:message])
end
return post("#{working_domain}/messages.mime", data)
end
post("#{working_domain}/messages", data)
when MessageBuilder
post("#{working_domain}/messages", data.message)
else
fail ParameterError.new('Unknown data type for data parameter.', data)
end
end | ruby | def send_message(working_domain, data)
if test_mode? then
Mailgun::Client.deliveries << data
return Response.from_hash(
{
:body => '{"id": "test-mode-mail@localhost", "message": "Queued. Thank you."}',
:code => 200,
}
)
end
case data
when Hash
# Remove nil values from the data hash
# Submitting nils to the API will likely cause an error.
# See also: https://github.com/mailgun/mailgun-ruby/issues/32
data = data.select { |k, v| v != nil }
if data.key?(:message)
if data[:message].is_a?(String)
data[:message] = convert_string_to_file(data[:message])
end
return post("#{working_domain}/messages.mime", data)
end
post("#{working_domain}/messages", data)
when MessageBuilder
post("#{working_domain}/messages", data.message)
else
fail ParameterError.new('Unknown data type for data parameter.', data)
end
end | [
"def",
"send_message",
"(",
"working_domain",
",",
"data",
")",
"if",
"test_mode?",
"then",
"Mailgun",
"::",
"Client",
".",
"deliveries",
"<<",
"data",
"return",
"Response",
".",
"from_hash",
"(",
"{",
":body",
"=>",
"'{\"id\": \"test-mode-mail@localhost\", \"message\": \"Queued. Thank you.\"}'",
",",
":code",
"=>",
"200",
",",
"}",
")",
"end",
"case",
"data",
"when",
"Hash",
"# Remove nil values from the data hash",
"# Submitting nils to the API will likely cause an error.",
"# See also: https://github.com/mailgun/mailgun-ruby/issues/32",
"data",
"=",
"data",
".",
"select",
"{",
"|",
"k",
",",
"v",
"|",
"v",
"!=",
"nil",
"}",
"if",
"data",
".",
"key?",
"(",
":message",
")",
"if",
"data",
"[",
":message",
"]",
".",
"is_a?",
"(",
"String",
")",
"data",
"[",
":message",
"]",
"=",
"convert_string_to_file",
"(",
"data",
"[",
":message",
"]",
")",
"end",
"return",
"post",
"(",
"\"#{working_domain}/messages.mime\"",
",",
"data",
")",
"end",
"post",
"(",
"\"#{working_domain}/messages\"",
",",
"data",
")",
"when",
"MessageBuilder",
"post",
"(",
"\"#{working_domain}/messages\"",
",",
"data",
".",
"message",
")",
"else",
"fail",
"ParameterError",
".",
"new",
"(",
"'Unknown data type for data parameter.'",
",",
"data",
")",
"end",
"end"
] | Simple Message Sending
@param [String] working_domain This is the domain you wish to send from.
@param [Hash] data This should be a standard Hash
containing required parameters for the requested resource.
@return [Mailgun::Response] A Mailgun::Response object. | [
"Simple",
"Message",
"Sending"
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/client.rb#L63-L93 | train |
mailgun/mailgun-ruby | lib/mailgun/client.rb | Mailgun.Client.post | def post(resource_path, data, headers = {})
response = @http_client[resource_path].post(data, headers)
Response.new(response)
rescue => err
raise communication_error err
end | ruby | def post(resource_path, data, headers = {})
response = @http_client[resource_path].post(data, headers)
Response.new(response)
rescue => err
raise communication_error err
end | [
"def",
"post",
"(",
"resource_path",
",",
"data",
",",
"headers",
"=",
"{",
"}",
")",
"response",
"=",
"@http_client",
"[",
"resource_path",
"]",
".",
"post",
"(",
"data",
",",
"headers",
")",
"Response",
".",
"new",
"(",
"response",
")",
"rescue",
"=>",
"err",
"raise",
"communication_error",
"err",
"end"
] | Generic Mailgun POST Handler
@param [String] resource_path This is the API resource you wish to interact
with. Be sure to include your domain, where necessary.
@param [Hash] data This should be a standard Hash
containing required parameters for the requested resource.
@param [Hash] headers Additional headers to pass to the resource.
@return [Mailgun::Response] A Mailgun::Response object. | [
"Generic",
"Mailgun",
"POST",
"Handler"
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/client.rb#L103-L108 | train |
mailgun/mailgun-ruby | lib/mailgun/client.rb | Mailgun.Client.get | def get(resource_path, params = nil, accept = '*/*')
if params
response = @http_client[resource_path].get(params: params, accept: accept)
else
response = @http_client[resource_path].get(accept: accept)
end
Response.new(response)
rescue => err
raise communication_error err
end | ruby | def get(resource_path, params = nil, accept = '*/*')
if params
response = @http_client[resource_path].get(params: params, accept: accept)
else
response = @http_client[resource_path].get(accept: accept)
end
Response.new(response)
rescue => err
raise communication_error err
end | [
"def",
"get",
"(",
"resource_path",
",",
"params",
"=",
"nil",
",",
"accept",
"=",
"'*/*'",
")",
"if",
"params",
"response",
"=",
"@http_client",
"[",
"resource_path",
"]",
".",
"get",
"(",
"params",
":",
"params",
",",
"accept",
":",
"accept",
")",
"else",
"response",
"=",
"@http_client",
"[",
"resource_path",
"]",
".",
"get",
"(",
"accept",
":",
"accept",
")",
"end",
"Response",
".",
"new",
"(",
"response",
")",
"rescue",
"=>",
"err",
"raise",
"communication_error",
"err",
"end"
] | Generic Mailgun GET Handler
@param [String] resource_path This is the API resource you wish to interact
with. Be sure to include your domain, where necessary.
@param [Hash] params This should be a standard Hash
containing required parameters for the requested resource.
@param [String] accept Acceptable Content-Type of the response body.
@return [Mailgun::Response] A Mailgun::Response object. | [
"Generic",
"Mailgun",
"GET",
"Handler"
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/client.rb#L118-L127 | train |
mailgun/mailgun-ruby | lib/mailgun/client.rb | Mailgun.Client.put | def put(resource_path, data)
response = @http_client[resource_path].put(data)
Response.new(response)
rescue => err
raise communication_error err
end | ruby | def put(resource_path, data)
response = @http_client[resource_path].put(data)
Response.new(response)
rescue => err
raise communication_error err
end | [
"def",
"put",
"(",
"resource_path",
",",
"data",
")",
"response",
"=",
"@http_client",
"[",
"resource_path",
"]",
".",
"put",
"(",
"data",
")",
"Response",
".",
"new",
"(",
"response",
")",
"rescue",
"=>",
"err",
"raise",
"communication_error",
"err",
"end"
] | Generic Mailgun PUT Handler
@param [String] resource_path This is the API resource you wish to interact
with. Be sure to include your domain, where necessary.
@param [Hash] data This should be a standard Hash
containing required parameters for the requested resource.
@return [Mailgun::Response] A Mailgun::Response object. | [
"Generic",
"Mailgun",
"PUT",
"Handler"
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/client.rb#L136-L141 | train |
mailgun/mailgun-ruby | lib/mailgun/client.rb | Mailgun.Client.delete | def delete(resource_path)
response = @http_client[resource_path].delete
Response.new(response)
rescue => err
raise communication_error err
end | ruby | def delete(resource_path)
response = @http_client[resource_path].delete
Response.new(response)
rescue => err
raise communication_error err
end | [
"def",
"delete",
"(",
"resource_path",
")",
"response",
"=",
"@http_client",
"[",
"resource_path",
"]",
".",
"delete",
"Response",
".",
"new",
"(",
"response",
")",
"rescue",
"=>",
"err",
"raise",
"communication_error",
"err",
"end"
] | Generic Mailgun DELETE Handler
@param [String] resource_path This is the API resource you wish to interact
with. Be sure to include your domain, where necessary.
@return [Mailgun::Response] A Mailgun::Response object. | [
"Generic",
"Mailgun",
"DELETE",
"Handler"
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/client.rb#L148-L153 | train |
mailgun/mailgun-ruby | lib/mailgun/client.rb | Mailgun.Client.convert_string_to_file | def convert_string_to_file(string)
file = Tempfile.new('MG_TMP_MIME')
file.write(string)
file.rewind
file
end | ruby | def convert_string_to_file(string)
file = Tempfile.new('MG_TMP_MIME')
file.write(string)
file.rewind
file
end | [
"def",
"convert_string_to_file",
"(",
"string",
")",
"file",
"=",
"Tempfile",
".",
"new",
"(",
"'MG_TMP_MIME'",
")",
"file",
".",
"write",
"(",
"string",
")",
"file",
".",
"rewind",
"file",
"end"
] | Converts MIME string to file for easy uploading to API
@param [String] string MIME string to post to API
@return [File] File object | [
"Converts",
"MIME",
"string",
"to",
"file",
"for",
"easy",
"uploading",
"to",
"API"
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/client.rb#L169-L174 | train |
mailgun/mailgun-ruby | lib/mailgun/client.rb | Mailgun.Client.communication_error | def communication_error(e)
return CommunicationError.new(e.message, e.response) if e.respond_to? :response
CommunicationError.new(e.message)
end | ruby | def communication_error(e)
return CommunicationError.new(e.message, e.response) if e.respond_to? :response
CommunicationError.new(e.message)
end | [
"def",
"communication_error",
"(",
"e",
")",
"return",
"CommunicationError",
".",
"new",
"(",
"e",
".",
"message",
",",
"e",
".",
"response",
")",
"if",
"e",
".",
"respond_to?",
":response",
"CommunicationError",
".",
"new",
"(",
"e",
".",
"message",
")",
"end"
] | Raises CommunicationError and stores response in it if present
@param [StandardException] e upstream exception object | [
"Raises",
"CommunicationError",
"and",
"stores",
"response",
"in",
"it",
"if",
"present"
] | 265efffd51209b0170a3225bbe945b649643465a | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/client.rb#L195-L198 | train |
theforeman/foreman_ansible | app/services/foreman_ansible/fact_parser.rb | ForemanAnsible.FactParser.get_interfaces | def get_interfaces # rubocop:disable Naming/AccessorMethodName
pref = facts[:ansible_default_ipv4] &&
facts[:ansible_default_ipv4]['interface']
if pref.present?
(facts[:ansible_interfaces] - [pref]).unshift(pref)
else
ansible_interfaces
end
end | ruby | def get_interfaces # rubocop:disable Naming/AccessorMethodName
pref = facts[:ansible_default_ipv4] &&
facts[:ansible_default_ipv4]['interface']
if pref.present?
(facts[:ansible_interfaces] - [pref]).unshift(pref)
else
ansible_interfaces
end
end | [
"def",
"get_interfaces",
"# rubocop:disable Naming/AccessorMethodName",
"pref",
"=",
"facts",
"[",
":ansible_default_ipv4",
"]",
"&&",
"facts",
"[",
":ansible_default_ipv4",
"]",
"[",
"'interface'",
"]",
"if",
"pref",
".",
"present?",
"(",
"facts",
"[",
":ansible_interfaces",
"]",
"-",
"[",
"pref",
"]",
")",
".",
"unshift",
"(",
"pref",
")",
"else",
"ansible_interfaces",
"end",
"end"
] | Move ansible's default interface first in the list of interfaces since
Foreman picks the first one that is usable. If ansible has no
preference otherwise at least sort the list.
This method overrides app/services/fact_parser.rb on Foreman and returns
an array of interface names, ['eth0', 'wlan1', etc...] | [
"Move",
"ansible",
"s",
"default",
"interface",
"first",
"in",
"the",
"list",
"of",
"interfaces",
"since",
"Foreman",
"picks",
"the",
"first",
"one",
"that",
"is",
"usable",
".",
"If",
"ansible",
"has",
"no",
"preference",
"otherwise",
"at",
"least",
"sort",
"the",
"list",
"."
] | e805df4ba6f4366423b369c5746a58fc662034d8 | https://github.com/theforeman/foreman_ansible/blob/e805df4ba6f4366423b369c5746a58fc662034d8/app/services/foreman_ansible/fact_parser.rb#L44-L52 | train |
samvera/browse-everything | lib/browse_everything/retriever.rb | BrowseEverything.Retriever.download | def download(spec, target = nil)
if target.nil?
ext = File.extname(spec['file_name'])
base = File.basename(spec['file_name'], ext)
target = Dir::Tmpname.create([base, ext]) {}
end
File.open(target, 'wb') do |output|
retrieve(spec) do |chunk, retrieved, total|
output.write(chunk)
yield(target, retrieved, total) if block_given?
end
end
target
end | ruby | def download(spec, target = nil)
if target.nil?
ext = File.extname(spec['file_name'])
base = File.basename(spec['file_name'], ext)
target = Dir::Tmpname.create([base, ext]) {}
end
File.open(target, 'wb') do |output|
retrieve(spec) do |chunk, retrieved, total|
output.write(chunk)
yield(target, retrieved, total) if block_given?
end
end
target
end | [
"def",
"download",
"(",
"spec",
",",
"target",
"=",
"nil",
")",
"if",
"target",
".",
"nil?",
"ext",
"=",
"File",
".",
"extname",
"(",
"spec",
"[",
"'file_name'",
"]",
")",
"base",
"=",
"File",
".",
"basename",
"(",
"spec",
"[",
"'file_name'",
"]",
",",
"ext",
")",
"target",
"=",
"Dir",
"::",
"Tmpname",
".",
"create",
"(",
"[",
"base",
",",
"ext",
"]",
")",
"{",
"}",
"end",
"File",
".",
"open",
"(",
"target",
",",
"'wb'",
")",
"do",
"|",
"output",
"|",
"retrieve",
"(",
"spec",
")",
"do",
"|",
"chunk",
",",
"retrieved",
",",
"total",
"|",
"output",
".",
"write",
"(",
"chunk",
")",
"yield",
"(",
"target",
",",
"retrieved",
",",
"total",
")",
"if",
"block_given?",
"end",
"end",
"target",
"end"
] | Constructor
Download a file or resource
@param options [Hash]
@param target [String, nil] system path to the downloaded file (defaults to a temporary file) | [
"Constructor",
"Download",
"a",
"file",
"or",
"resource"
] | adf89baef6b0ddc0c88eab853b2b0cbbc845be21 | https://github.com/samvera/browse-everything/blob/adf89baef6b0ddc0c88eab853b2b0cbbc845be21/lib/browse_everything/retriever.rb#L52-L66 | train |
samvera/browse-everything | lib/browse_everything/retriever.rb | BrowseEverything.Retriever.retrieve | def retrieve(options, &block)
expiry_time_value = options.fetch('expires', nil)
if expiry_time_value
expiry_time = Time.parse(expiry_time_value)
raise ArgumentError, "Download expired at #{expiry_time}" if expiry_time < Time.now
end
download_options = extract_download_options(options)
url = download_options[:url]
case url.scheme
when 'file'
retrieve_file(download_options, &block)
when /https?/
retrieve_http(download_options, &block)
else
raise URI::BadURIError, "Unknown URI scheme: #{url.scheme}"
end
end | ruby | def retrieve(options, &block)
expiry_time_value = options.fetch('expires', nil)
if expiry_time_value
expiry_time = Time.parse(expiry_time_value)
raise ArgumentError, "Download expired at #{expiry_time}" if expiry_time < Time.now
end
download_options = extract_download_options(options)
url = download_options[:url]
case url.scheme
when 'file'
retrieve_file(download_options, &block)
when /https?/
retrieve_http(download_options, &block)
else
raise URI::BadURIError, "Unknown URI scheme: #{url.scheme}"
end
end | [
"def",
"retrieve",
"(",
"options",
",",
"&",
"block",
")",
"expiry_time_value",
"=",
"options",
".",
"fetch",
"(",
"'expires'",
",",
"nil",
")",
"if",
"expiry_time_value",
"expiry_time",
"=",
"Time",
".",
"parse",
"(",
"expiry_time_value",
")",
"raise",
"ArgumentError",
",",
"\"Download expired at #{expiry_time}\"",
"if",
"expiry_time",
"<",
"Time",
".",
"now",
"end",
"download_options",
"=",
"extract_download_options",
"(",
"options",
")",
"url",
"=",
"download_options",
"[",
":url",
"]",
"case",
"url",
".",
"scheme",
"when",
"'file'",
"retrieve_file",
"(",
"download_options",
",",
"block",
")",
"when",
"/",
"/",
"retrieve_http",
"(",
"download_options",
",",
"block",
")",
"else",
"raise",
"URI",
"::",
"BadURIError",
",",
"\"Unknown URI scheme: #{url.scheme}\"",
"end",
"end"
] | Retrieve the resource from the storage service
@param options [Hash] | [
"Retrieve",
"the",
"resource",
"from",
"the",
"storage",
"service"
] | adf89baef6b0ddc0c88eab853b2b0cbbc845be21 | https://github.com/samvera/browse-everything/blob/adf89baef6b0ddc0c88eab853b2b0cbbc845be21/lib/browse_everything/retriever.rb#L70-L88 | train |
samvera/browse-everything | lib/browse_everything/retriever.rb | BrowseEverything.Retriever.extract_download_options | def extract_download_options(options)
url = options.fetch('url')
# This avoids the potential for a KeyError
headers = options.fetch('headers', {}) || {}
file_size_value = options.fetch('file_size', 0)
file_size = file_size_value.to_i
output = {
url: ::Addressable::URI.parse(url),
headers: headers,
file_size: file_size
}
output[:file_size] = get_file_size(output) if output[:file_size] < 1
output
end | ruby | def extract_download_options(options)
url = options.fetch('url')
# This avoids the potential for a KeyError
headers = options.fetch('headers', {}) || {}
file_size_value = options.fetch('file_size', 0)
file_size = file_size_value.to_i
output = {
url: ::Addressable::URI.parse(url),
headers: headers,
file_size: file_size
}
output[:file_size] = get_file_size(output) if output[:file_size] < 1
output
end | [
"def",
"extract_download_options",
"(",
"options",
")",
"url",
"=",
"options",
".",
"fetch",
"(",
"'url'",
")",
"# This avoids the potential for a KeyError",
"headers",
"=",
"options",
".",
"fetch",
"(",
"'headers'",
",",
"{",
"}",
")",
"||",
"{",
"}",
"file_size_value",
"=",
"options",
".",
"fetch",
"(",
"'file_size'",
",",
"0",
")",
"file_size",
"=",
"file_size_value",
".",
"to_i",
"output",
"=",
"{",
"url",
":",
"::",
"Addressable",
"::",
"URI",
".",
"parse",
"(",
"url",
")",
",",
"headers",
":",
"headers",
",",
"file_size",
":",
"file_size",
"}",
"output",
"[",
":file_size",
"]",
"=",
"get_file_size",
"(",
"output",
")",
"if",
"output",
"[",
":file_size",
"]",
"<",
"1",
"output",
"end"
] | Extract and parse options used to download a file or resource from an HTTP API
@param options [Hash]
@return [Hash] | [
"Extract",
"and",
"parse",
"options",
"used",
"to",
"download",
"a",
"file",
"or",
"resource",
"from",
"an",
"HTTP",
"API"
] | adf89baef6b0ddc0c88eab853b2b0cbbc845be21 | https://github.com/samvera/browse-everything/blob/adf89baef6b0ddc0c88eab853b2b0cbbc845be21/lib/browse_everything/retriever.rb#L95-L112 | train |
samvera/browse-everything | lib/browse_everything/retriever.rb | BrowseEverything.Retriever.retrieve_file | def retrieve_file(options)
file_uri = options.fetch(:url)
file_size = options.fetch(:file_size)
retrieved = 0
File.open(file_uri.path, 'rb') do |f|
until f.eof?
chunk = f.read(chunk_size)
retrieved += chunk.length
yield(chunk, retrieved, file_size)
end
end
end | ruby | def retrieve_file(options)
file_uri = options.fetch(:url)
file_size = options.fetch(:file_size)
retrieved = 0
File.open(file_uri.path, 'rb') do |f|
until f.eof?
chunk = f.read(chunk_size)
retrieved += chunk.length
yield(chunk, retrieved, file_size)
end
end
end | [
"def",
"retrieve_file",
"(",
"options",
")",
"file_uri",
"=",
"options",
".",
"fetch",
"(",
":url",
")",
"file_size",
"=",
"options",
".",
"fetch",
"(",
":file_size",
")",
"retrieved",
"=",
"0",
"File",
".",
"open",
"(",
"file_uri",
".",
"path",
",",
"'rb'",
")",
"do",
"|",
"f",
"|",
"until",
"f",
".",
"eof?",
"chunk",
"=",
"f",
".",
"read",
"(",
"chunk_size",
")",
"retrieved",
"+=",
"chunk",
".",
"length",
"yield",
"(",
"chunk",
",",
"retrieved",
",",
"file_size",
")",
"end",
"end",
"end"
] | Retrieve the file from the file system
@param options [Hash] | [
"Retrieve",
"the",
"file",
"from",
"the",
"file",
"system"
] | adf89baef6b0ddc0c88eab853b2b0cbbc845be21 | https://github.com/samvera/browse-everything/blob/adf89baef6b0ddc0c88eab853b2b0cbbc845be21/lib/browse_everything/retriever.rb#L116-L128 | train |
samvera/browse-everything | lib/browse_everything/retriever.rb | BrowseEverything.Retriever.retrieve_http | def retrieve_http(options)
file_size = options.fetch(:file_size)
headers = options.fetch(:headers)
url = options.fetch(:url)
retrieved = 0
request = Typhoeus::Request.new(url.to_s, method: :get, headers: headers)
request.on_headers do |response|
raise DownloadError.new("#{self.class}: Failed to download #{url}: Status Code: #{response.code}", response) unless response.code == 200
end
request.on_body do |chunk|
retrieved += chunk.bytesize
yield(chunk, retrieved, file_size)
end
request.run
end | ruby | def retrieve_http(options)
file_size = options.fetch(:file_size)
headers = options.fetch(:headers)
url = options.fetch(:url)
retrieved = 0
request = Typhoeus::Request.new(url.to_s, method: :get, headers: headers)
request.on_headers do |response|
raise DownloadError.new("#{self.class}: Failed to download #{url}: Status Code: #{response.code}", response) unless response.code == 200
end
request.on_body do |chunk|
retrieved += chunk.bytesize
yield(chunk, retrieved, file_size)
end
request.run
end | [
"def",
"retrieve_http",
"(",
"options",
")",
"file_size",
"=",
"options",
".",
"fetch",
"(",
":file_size",
")",
"headers",
"=",
"options",
".",
"fetch",
"(",
":headers",
")",
"url",
"=",
"options",
".",
"fetch",
"(",
":url",
")",
"retrieved",
"=",
"0",
"request",
"=",
"Typhoeus",
"::",
"Request",
".",
"new",
"(",
"url",
".",
"to_s",
",",
"method",
":",
":get",
",",
"headers",
":",
"headers",
")",
"request",
".",
"on_headers",
"do",
"|",
"response",
"|",
"raise",
"DownloadError",
".",
"new",
"(",
"\"#{self.class}: Failed to download #{url}: Status Code: #{response.code}\"",
",",
"response",
")",
"unless",
"response",
".",
"code",
"==",
"200",
"end",
"request",
".",
"on_body",
"do",
"|",
"chunk",
"|",
"retrieved",
"+=",
"chunk",
".",
"bytesize",
"yield",
"(",
"chunk",
",",
"retrieved",
",",
"file_size",
")",
"end",
"request",
".",
"run",
"end"
] | Retrieve a resource over the HTTP
@param options [Hash] | [
"Retrieve",
"a",
"resource",
"over",
"the",
"HTTP"
] | adf89baef6b0ddc0c88eab853b2b0cbbc845be21 | https://github.com/samvera/browse-everything/blob/adf89baef6b0ddc0c88eab853b2b0cbbc845be21/lib/browse_everything/retriever.rb#L132-L147 | train |
samvera/browse-everything | lib/browse_everything/retriever.rb | BrowseEverything.Retriever.get_file_size | def get_file_size(options)
url = options.fetch(:url)
headers = options.fetch(:headers)
file_size = options.fetch(:file_size)
case url.scheme
when 'file'
File.size(url.path)
when /https?/
response = Typhoeus.head(url.to_s, headers: headers)
length_value = response.headers['Content-Length'] || file_size
length_value.to_i
else
raise URI::BadURIError, "Unknown URI scheme: #{url.scheme}"
end
end | ruby | def get_file_size(options)
url = options.fetch(:url)
headers = options.fetch(:headers)
file_size = options.fetch(:file_size)
case url.scheme
when 'file'
File.size(url.path)
when /https?/
response = Typhoeus.head(url.to_s, headers: headers)
length_value = response.headers['Content-Length'] || file_size
length_value.to_i
else
raise URI::BadURIError, "Unknown URI scheme: #{url.scheme}"
end
end | [
"def",
"get_file_size",
"(",
"options",
")",
"url",
"=",
"options",
".",
"fetch",
"(",
":url",
")",
"headers",
"=",
"options",
".",
"fetch",
"(",
":headers",
")",
"file_size",
"=",
"options",
".",
"fetch",
"(",
":file_size",
")",
"case",
"url",
".",
"scheme",
"when",
"'file'",
"File",
".",
"size",
"(",
"url",
".",
"path",
")",
"when",
"/",
"/",
"response",
"=",
"Typhoeus",
".",
"head",
"(",
"url",
".",
"to_s",
",",
"headers",
":",
"headers",
")",
"length_value",
"=",
"response",
".",
"headers",
"[",
"'Content-Length'",
"]",
"||",
"file_size",
"length_value",
".",
"to_i",
"else",
"raise",
"URI",
"::",
"BadURIError",
",",
"\"Unknown URI scheme: #{url.scheme}\"",
"end",
"end"
] | Retrieve the file size
@param options [Hash]
@return [Integer] the size of the requested file | [
"Retrieve",
"the",
"file",
"size"
] | adf89baef6b0ddc0c88eab853b2b0cbbc845be21 | https://github.com/samvera/browse-everything/blob/adf89baef6b0ddc0c88eab853b2b0cbbc845be21/lib/browse_everything/retriever.rb#L152-L167 | train |
njh/ruby-mqtt | lib/mqtt/packet.rb | MQTT.Packet.update_attributes | def update_attributes(attr = {})
attr.each_pair do |k, v|
if v.is_a?(Array) || v.is_a?(Hash)
send("#{k}=", v.dup)
else
send("#{k}=", v)
end
end
end | ruby | def update_attributes(attr = {})
attr.each_pair do |k, v|
if v.is_a?(Array) || v.is_a?(Hash)
send("#{k}=", v.dup)
else
send("#{k}=", v)
end
end
end | [
"def",
"update_attributes",
"(",
"attr",
"=",
"{",
"}",
")",
"attr",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"v",
".",
"is_a?",
"(",
"Array",
")",
"||",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"send",
"(",
"\"#{k}=\"",
",",
"v",
".",
"dup",
")",
"else",
"send",
"(",
"\"#{k}=\"",
",",
"v",
")",
"end",
"end",
"end"
] | Create a new empty packet
Set packet attributes from a hash of attribute names and values | [
"Create",
"a",
"new",
"empty",
"packet",
"Set",
"packet",
"attributes",
"from",
"a",
"hash",
"of",
"attribute",
"names",
"and",
"values"
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/packet.rb#L126-L134 | train |
njh/ruby-mqtt | lib/mqtt/packet.rb | MQTT.Packet.to_s | def to_s
# Encode the fixed header
header = [
((type_id.to_i & 0x0F) << 4) |
(flags[3] ? 0x8 : 0x0) |
(flags[2] ? 0x4 : 0x0) |
(flags[1] ? 0x2 : 0x0) |
(flags[0] ? 0x1 : 0x0)
]
# Get the packet's variable header and payload
body = encode_body
# Check that that packet isn't too big
body_length = body.bytesize
if body_length > 268_435_455
raise 'Error serialising packet: body is more than 256MB'
end
# Build up the body length field bytes
loop do
digit = (body_length % 128)
body_length = body_length.div(128)
# if there are more digits to encode, set the top bit of this digit
digit |= 0x80 if body_length > 0
header.push(digit)
break if body_length <= 0
end
# Convert header to binary and add on body
header.pack('C*') + body
end | ruby | def to_s
# Encode the fixed header
header = [
((type_id.to_i & 0x0F) << 4) |
(flags[3] ? 0x8 : 0x0) |
(flags[2] ? 0x4 : 0x0) |
(flags[1] ? 0x2 : 0x0) |
(flags[0] ? 0x1 : 0x0)
]
# Get the packet's variable header and payload
body = encode_body
# Check that that packet isn't too big
body_length = body.bytesize
if body_length > 268_435_455
raise 'Error serialising packet: body is more than 256MB'
end
# Build up the body length field bytes
loop do
digit = (body_length % 128)
body_length = body_length.div(128)
# if there are more digits to encode, set the top bit of this digit
digit |= 0x80 if body_length > 0
header.push(digit)
break if body_length <= 0
end
# Convert header to binary and add on body
header.pack('C*') + body
end | [
"def",
"to_s",
"# Encode the fixed header",
"header",
"=",
"[",
"(",
"(",
"type_id",
".",
"to_i",
"&",
"0x0F",
")",
"<<",
"4",
")",
"|",
"(",
"flags",
"[",
"3",
"]",
"?",
"0x8",
":",
"0x0",
")",
"|",
"(",
"flags",
"[",
"2",
"]",
"?",
"0x4",
":",
"0x0",
")",
"|",
"(",
"flags",
"[",
"1",
"]",
"?",
"0x2",
":",
"0x0",
")",
"|",
"(",
"flags",
"[",
"0",
"]",
"?",
"0x1",
":",
"0x0",
")",
"]",
"# Get the packet's variable header and payload",
"body",
"=",
"encode_body",
"# Check that that packet isn't too big",
"body_length",
"=",
"body",
".",
"bytesize",
"if",
"body_length",
">",
"268_435_455",
"raise",
"'Error serialising packet: body is more than 256MB'",
"end",
"# Build up the body length field bytes",
"loop",
"do",
"digit",
"=",
"(",
"body_length",
"%",
"128",
")",
"body_length",
"=",
"body_length",
".",
"div",
"(",
"128",
")",
"# if there are more digits to encode, set the top bit of this digit",
"digit",
"|=",
"0x80",
"if",
"body_length",
">",
"0",
"header",
".",
"push",
"(",
"digit",
")",
"break",
"if",
"body_length",
"<=",
"0",
"end",
"# Convert header to binary and add on body",
"header",
".",
"pack",
"(",
"'C*'",
")",
"+",
"body",
"end"
] | Serialise the packet | [
"Serialise",
"the",
"packet"
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/packet.rb#L174-L205 | train |
njh/ruby-mqtt | lib/mqtt/packet.rb | MQTT.Packet.shift_bits | def shift_bits(buffer)
buffer.slice!(0...1).unpack('b8').first.split('').map { |b| b == '1' }
end | ruby | def shift_bits(buffer)
buffer.slice!(0...1).unpack('b8').first.split('').map { |b| b == '1' }
end | [
"def",
"shift_bits",
"(",
"buffer",
")",
"buffer",
".",
"slice!",
"(",
"0",
"...",
"1",
")",
".",
"unpack",
"(",
"'b8'",
")",
".",
"first",
".",
"split",
"(",
"''",
")",
".",
"map",
"{",
"|",
"b",
"|",
"b",
"==",
"'1'",
"}",
"end"
] | Remove 8 bits from the front of buffer | [
"Remove",
"8",
"bits",
"from",
"the",
"front",
"of",
"buffer"
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/packet.rb#L268-L270 | train |
njh/ruby-mqtt | lib/mqtt/packet.rb | MQTT.Packet.shift_string | def shift_string(buffer)
len = shift_short(buffer)
str = shift_data(buffer, len)
# Strings in MQTT v3.1 are all UTF-8
str.force_encoding('UTF-8')
end | ruby | def shift_string(buffer)
len = shift_short(buffer)
str = shift_data(buffer, len)
# Strings in MQTT v3.1 are all UTF-8
str.force_encoding('UTF-8')
end | [
"def",
"shift_string",
"(",
"buffer",
")",
"len",
"=",
"shift_short",
"(",
"buffer",
")",
"str",
"=",
"shift_data",
"(",
"buffer",
",",
"len",
")",
"# Strings in MQTT v3.1 are all UTF-8",
"str",
".",
"force_encoding",
"(",
"'UTF-8'",
")",
"end"
] | Remove string from the front of buffer | [
"Remove",
"string",
"from",
"the",
"front",
"of",
"buffer"
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/packet.rb#L278-L283 | train |
njh/ruby-mqtt | lib/mqtt/client.rb | MQTT.Client.key_file= | def key_file=(*args)
path, passphrase = args.flatten
ssl_context.key = OpenSSL::PKey::RSA.new(File.open(path), passphrase)
end | ruby | def key_file=(*args)
path, passphrase = args.flatten
ssl_context.key = OpenSSL::PKey::RSA.new(File.open(path), passphrase)
end | [
"def",
"key_file",
"=",
"(",
"*",
"args",
")",
"path",
",",
"passphrase",
"=",
"args",
".",
"flatten",
"ssl_context",
".",
"key",
"=",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"new",
"(",
"File",
".",
"open",
"(",
"path",
")",
",",
"passphrase",
")",
"end"
] | Set a path to a file containing a PEM-format client private key | [
"Set",
"a",
"path",
"to",
"a",
"file",
"containing",
"a",
"PEM",
"-",
"format",
"client",
"private",
"key"
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/client.rb#L188-L191 | train |
njh/ruby-mqtt | lib/mqtt/client.rb | MQTT.Client.key= | def key=(*args)
cert, passphrase = args.flatten
ssl_context.key = OpenSSL::PKey::RSA.new(cert, passphrase)
end | ruby | def key=(*args)
cert, passphrase = args.flatten
ssl_context.key = OpenSSL::PKey::RSA.new(cert, passphrase)
end | [
"def",
"key",
"=",
"(",
"*",
"args",
")",
"cert",
",",
"passphrase",
"=",
"args",
".",
"flatten",
"ssl_context",
".",
"key",
"=",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"new",
"(",
"cert",
",",
"passphrase",
")",
"end"
] | Set to a PEM-format client private key | [
"Set",
"to",
"a",
"PEM",
"-",
"format",
"client",
"private",
"key"
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/client.rb#L194-L197 | train |
njh/ruby-mqtt | lib/mqtt/client.rb | MQTT.Client.ca_file= | def ca_file=(path)
ssl_context.ca_file = path
ssl_context.verify_mode = OpenSSL::SSL::VERIFY_PEER unless path.nil?
end | ruby | def ca_file=(path)
ssl_context.ca_file = path
ssl_context.verify_mode = OpenSSL::SSL::VERIFY_PEER unless path.nil?
end | [
"def",
"ca_file",
"=",
"(",
"path",
")",
"ssl_context",
".",
"ca_file",
"=",
"path",
"ssl_context",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_PEER",
"unless",
"path",
".",
"nil?",
"end"
] | Set a path to a file containing a PEM-format CA certificate and enable peer verification | [
"Set",
"a",
"path",
"to",
"a",
"file",
"containing",
"a",
"PEM",
"-",
"format",
"CA",
"certificate",
"and",
"enable",
"peer",
"verification"
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/client.rb#L200-L203 | train |
njh/ruby-mqtt | lib/mqtt/client.rb | MQTT.Client.set_will | def set_will(topic, payload, retain = false, qos = 0)
self.will_topic = topic
self.will_payload = payload
self.will_retain = retain
self.will_qos = qos
end | ruby | def set_will(topic, payload, retain = false, qos = 0)
self.will_topic = topic
self.will_payload = payload
self.will_retain = retain
self.will_qos = qos
end | [
"def",
"set_will",
"(",
"topic",
",",
"payload",
",",
"retain",
"=",
"false",
",",
"qos",
"=",
"0",
")",
"self",
".",
"will_topic",
"=",
"topic",
"self",
".",
"will_payload",
"=",
"payload",
"self",
".",
"will_retain",
"=",
"retain",
"self",
".",
"will_qos",
"=",
"qos",
"end"
] | Set the Will for the client
The will is a message that will be delivered by the server when the client dies.
The Will must be set before establishing a connection to the server | [
"Set",
"the",
"Will",
"for",
"the",
"client"
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/client.rb#L209-L214 | train |
njh/ruby-mqtt | lib/mqtt/client.rb | MQTT.Client.connect | def connect(clientid = nil)
@client_id = clientid unless clientid.nil?
if @client_id.nil? || @client_id.empty?
raise 'Must provide a client_id if clean_session is set to false' unless @clean_session
# Empty client id is not allowed for version 3.1.0
@client_id = MQTT::Client.generate_client_id if @version == '3.1.0'
end
raise 'No MQTT server host set when attempting to connect' if @host.nil?
unless connected?
# Create network socket
tcp_socket = TCPSocket.new(@host, @port)
if @ssl
# Set the protocol version
ssl_context.ssl_version = @ssl if @ssl.is_a?(Symbol)
@socket = OpenSSL::SSL::SSLSocket.new(tcp_socket, ssl_context)
@socket.sync_close = true
# Set hostname on secure socket for Server Name Indication (SNI)
@socket.hostname = @host if @socket.respond_to?(:hostname=)
@socket.connect
else
@socket = tcp_socket
end
# Construct a connect packet
packet = MQTT::Packet::Connect.new(
:version => @version,
:clean_session => @clean_session,
:keep_alive => @keep_alive,
:client_id => @client_id,
:username => @username,
:password => @password,
:will_topic => @will_topic,
:will_payload => @will_payload,
:will_qos => @will_qos,
:will_retain => @will_retain
)
# Send packet
send_packet(packet)
# Receive response
receive_connack
# Start packet reading thread
@read_thread = Thread.new(Thread.current) do |parent|
Thread.current[:parent] = parent
receive_packet while connected?
end
end
return unless block_given?
# If a block is given, then yield and disconnect
begin
yield(self)
ensure
disconnect
end
end | ruby | def connect(clientid = nil)
@client_id = clientid unless clientid.nil?
if @client_id.nil? || @client_id.empty?
raise 'Must provide a client_id if clean_session is set to false' unless @clean_session
# Empty client id is not allowed for version 3.1.0
@client_id = MQTT::Client.generate_client_id if @version == '3.1.0'
end
raise 'No MQTT server host set when attempting to connect' if @host.nil?
unless connected?
# Create network socket
tcp_socket = TCPSocket.new(@host, @port)
if @ssl
# Set the protocol version
ssl_context.ssl_version = @ssl if @ssl.is_a?(Symbol)
@socket = OpenSSL::SSL::SSLSocket.new(tcp_socket, ssl_context)
@socket.sync_close = true
# Set hostname on secure socket for Server Name Indication (SNI)
@socket.hostname = @host if @socket.respond_to?(:hostname=)
@socket.connect
else
@socket = tcp_socket
end
# Construct a connect packet
packet = MQTT::Packet::Connect.new(
:version => @version,
:clean_session => @clean_session,
:keep_alive => @keep_alive,
:client_id => @client_id,
:username => @username,
:password => @password,
:will_topic => @will_topic,
:will_payload => @will_payload,
:will_qos => @will_qos,
:will_retain => @will_retain
)
# Send packet
send_packet(packet)
# Receive response
receive_connack
# Start packet reading thread
@read_thread = Thread.new(Thread.current) do |parent|
Thread.current[:parent] = parent
receive_packet while connected?
end
end
return unless block_given?
# If a block is given, then yield and disconnect
begin
yield(self)
ensure
disconnect
end
end | [
"def",
"connect",
"(",
"clientid",
"=",
"nil",
")",
"@client_id",
"=",
"clientid",
"unless",
"clientid",
".",
"nil?",
"if",
"@client_id",
".",
"nil?",
"||",
"@client_id",
".",
"empty?",
"raise",
"'Must provide a client_id if clean_session is set to false'",
"unless",
"@clean_session",
"# Empty client id is not allowed for version 3.1.0",
"@client_id",
"=",
"MQTT",
"::",
"Client",
".",
"generate_client_id",
"if",
"@version",
"==",
"'3.1.0'",
"end",
"raise",
"'No MQTT server host set when attempting to connect'",
"if",
"@host",
".",
"nil?",
"unless",
"connected?",
"# Create network socket",
"tcp_socket",
"=",
"TCPSocket",
".",
"new",
"(",
"@host",
",",
"@port",
")",
"if",
"@ssl",
"# Set the protocol version",
"ssl_context",
".",
"ssl_version",
"=",
"@ssl",
"if",
"@ssl",
".",
"is_a?",
"(",
"Symbol",
")",
"@socket",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"SSLSocket",
".",
"new",
"(",
"tcp_socket",
",",
"ssl_context",
")",
"@socket",
".",
"sync_close",
"=",
"true",
"# Set hostname on secure socket for Server Name Indication (SNI)",
"@socket",
".",
"hostname",
"=",
"@host",
"if",
"@socket",
".",
"respond_to?",
"(",
":hostname=",
")",
"@socket",
".",
"connect",
"else",
"@socket",
"=",
"tcp_socket",
"end",
"# Construct a connect packet",
"packet",
"=",
"MQTT",
"::",
"Packet",
"::",
"Connect",
".",
"new",
"(",
":version",
"=>",
"@version",
",",
":clean_session",
"=>",
"@clean_session",
",",
":keep_alive",
"=>",
"@keep_alive",
",",
":client_id",
"=>",
"@client_id",
",",
":username",
"=>",
"@username",
",",
":password",
"=>",
"@password",
",",
":will_topic",
"=>",
"@will_topic",
",",
":will_payload",
"=>",
"@will_payload",
",",
":will_qos",
"=>",
"@will_qos",
",",
":will_retain",
"=>",
"@will_retain",
")",
"# Send packet",
"send_packet",
"(",
"packet",
")",
"# Receive response",
"receive_connack",
"# Start packet reading thread",
"@read_thread",
"=",
"Thread",
".",
"new",
"(",
"Thread",
".",
"current",
")",
"do",
"|",
"parent",
"|",
"Thread",
".",
"current",
"[",
":parent",
"]",
"=",
"parent",
"receive_packet",
"while",
"connected?",
"end",
"end",
"return",
"unless",
"block_given?",
"# If a block is given, then yield and disconnect",
"begin",
"yield",
"(",
"self",
")",
"ensure",
"disconnect",
"end",
"end"
] | Connect to the MQTT server
If a block is given, then yield to that block and then disconnect again. | [
"Connect",
"to",
"the",
"MQTT",
"server",
"If",
"a",
"block",
"is",
"given",
"then",
"yield",
"to",
"that",
"block",
"and",
"then",
"disconnect",
"again",
"."
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/client.rb#L218-L284 | train |
njh/ruby-mqtt | lib/mqtt/client.rb | MQTT.Client.disconnect | def disconnect(send_msg = true)
# Stop reading packets from the socket first
@read_thread.kill if @read_thread && @read_thread.alive?
@read_thread = nil
return unless connected?
# Close the socket if it is open
if send_msg
packet = MQTT::Packet::Disconnect.new
send_packet(packet)
end
@socket.close unless @socket.nil?
@socket = nil
end | ruby | def disconnect(send_msg = true)
# Stop reading packets from the socket first
@read_thread.kill if @read_thread && @read_thread.alive?
@read_thread = nil
return unless connected?
# Close the socket if it is open
if send_msg
packet = MQTT::Packet::Disconnect.new
send_packet(packet)
end
@socket.close unless @socket.nil?
@socket = nil
end | [
"def",
"disconnect",
"(",
"send_msg",
"=",
"true",
")",
"# Stop reading packets from the socket first",
"@read_thread",
".",
"kill",
"if",
"@read_thread",
"&&",
"@read_thread",
".",
"alive?",
"@read_thread",
"=",
"nil",
"return",
"unless",
"connected?",
"# Close the socket if it is open",
"if",
"send_msg",
"packet",
"=",
"MQTT",
"::",
"Packet",
"::",
"Disconnect",
".",
"new",
"send_packet",
"(",
"packet",
")",
"end",
"@socket",
".",
"close",
"unless",
"@socket",
".",
"nil?",
"@socket",
"=",
"nil",
"end"
] | Disconnect from the MQTT server.
If you don't want to say goodbye to the server, set send_msg to false. | [
"Disconnect",
"from",
"the",
"MQTT",
"server",
".",
"If",
"you",
"don",
"t",
"want",
"to",
"say",
"goodbye",
"to",
"the",
"server",
"set",
"send_msg",
"to",
"false",
"."
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/client.rb#L288-L302 | train |
njh/ruby-mqtt | lib/mqtt/client.rb | MQTT.Client.publish | def publish(topic, payload = '', retain = false, qos = 0)
raise ArgumentError, 'Topic name cannot be nil' if topic.nil?
raise ArgumentError, 'Topic name cannot be empty' if topic.empty?
packet = MQTT::Packet::Publish.new(
:id => next_packet_id,
:qos => qos,
:retain => retain,
:topic => topic,
:payload => payload
)
# Send the packet
res = send_packet(packet)
return if qos.zero?
Timeout.timeout(@ack_timeout) do
while connected?
@pubacks_semaphore.synchronize do
return res if @pubacks.delete(packet.id)
end
# FIXME: make threads communicate with each other, instead of polling
# (using a pipe and select ?)
sleep 0.01
end
end
-1
end | ruby | def publish(topic, payload = '', retain = false, qos = 0)
raise ArgumentError, 'Topic name cannot be nil' if topic.nil?
raise ArgumentError, 'Topic name cannot be empty' if topic.empty?
packet = MQTT::Packet::Publish.new(
:id => next_packet_id,
:qos => qos,
:retain => retain,
:topic => topic,
:payload => payload
)
# Send the packet
res = send_packet(packet)
return if qos.zero?
Timeout.timeout(@ack_timeout) do
while connected?
@pubacks_semaphore.synchronize do
return res if @pubacks.delete(packet.id)
end
# FIXME: make threads communicate with each other, instead of polling
# (using a pipe and select ?)
sleep 0.01
end
end
-1
end | [
"def",
"publish",
"(",
"topic",
",",
"payload",
"=",
"''",
",",
"retain",
"=",
"false",
",",
"qos",
"=",
"0",
")",
"raise",
"ArgumentError",
",",
"'Topic name cannot be nil'",
"if",
"topic",
".",
"nil?",
"raise",
"ArgumentError",
",",
"'Topic name cannot be empty'",
"if",
"topic",
".",
"empty?",
"packet",
"=",
"MQTT",
"::",
"Packet",
"::",
"Publish",
".",
"new",
"(",
":id",
"=>",
"next_packet_id",
",",
":qos",
"=>",
"qos",
",",
":retain",
"=>",
"retain",
",",
":topic",
"=>",
"topic",
",",
":payload",
"=>",
"payload",
")",
"# Send the packet",
"res",
"=",
"send_packet",
"(",
"packet",
")",
"return",
"if",
"qos",
".",
"zero?",
"Timeout",
".",
"timeout",
"(",
"@ack_timeout",
")",
"do",
"while",
"connected?",
"@pubacks_semaphore",
".",
"synchronize",
"do",
"return",
"res",
"if",
"@pubacks",
".",
"delete",
"(",
"packet",
".",
"id",
")",
"end",
"# FIXME: make threads communicate with each other, instead of polling",
"# (using a pipe and select ?)",
"sleep",
"0.01",
"end",
"end",
"-",
"1",
"end"
] | Publish a message on a particular topic to the MQTT server. | [
"Publish",
"a",
"message",
"on",
"a",
"particular",
"topic",
"to",
"the",
"MQTT",
"server",
"."
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/client.rb#L310-L339 | train |
njh/ruby-mqtt | lib/mqtt/client.rb | MQTT.Client.get | def get(topic = nil, options = {})
if block_given?
get_packet(topic) do |packet|
yield(packet.topic, packet.payload) unless packet.retain && options[:omit_retained]
end
else
loop do
# Wait for one packet to be available
packet = get_packet(topic)
return packet.topic, packet.payload unless packet.retain && options[:omit_retained]
end
end
end | ruby | def get(topic = nil, options = {})
if block_given?
get_packet(topic) do |packet|
yield(packet.topic, packet.payload) unless packet.retain && options[:omit_retained]
end
else
loop do
# Wait for one packet to be available
packet = get_packet(topic)
return packet.topic, packet.payload unless packet.retain && options[:omit_retained]
end
end
end | [
"def",
"get",
"(",
"topic",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"if",
"block_given?",
"get_packet",
"(",
"topic",
")",
"do",
"|",
"packet",
"|",
"yield",
"(",
"packet",
".",
"topic",
",",
"packet",
".",
"payload",
")",
"unless",
"packet",
".",
"retain",
"&&",
"options",
"[",
":omit_retained",
"]",
"end",
"else",
"loop",
"do",
"# Wait for one packet to be available",
"packet",
"=",
"get_packet",
"(",
"topic",
")",
"return",
"packet",
".",
"topic",
",",
"packet",
".",
"payload",
"unless",
"packet",
".",
"retain",
"&&",
"options",
"[",
":omit_retained",
"]",
"end",
"end",
"end"
] | Return the next message received from the MQTT server.
An optional topic can be given to subscribe to.
The method either returns the topic and message as an array:
topic,message = client.get
Or can be used with a block to keep processing messages:
client.get('test') do |topic,payload|
# Do stuff here
end | [
"Return",
"the",
"next",
"message",
"received",
"from",
"the",
"MQTT",
"server",
".",
"An",
"optional",
"topic",
"can",
"be",
"given",
"to",
"subscribe",
"to",
"."
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/client.rb#L372-L384 | train |
njh/ruby-mqtt | lib/mqtt/client.rb | MQTT.Client.get_packet | def get_packet(topic = nil)
# Subscribe to a topic, if an argument is given
subscribe(topic) unless topic.nil?
if block_given?
# Loop forever!
loop do
packet = @read_queue.pop
yield(packet)
puback_packet(packet) if packet.qos > 0
end
else
# Wait for one packet to be available
packet = @read_queue.pop
puback_packet(packet) if packet.qos > 0
return packet
end
end | ruby | def get_packet(topic = nil)
# Subscribe to a topic, if an argument is given
subscribe(topic) unless topic.nil?
if block_given?
# Loop forever!
loop do
packet = @read_queue.pop
yield(packet)
puback_packet(packet) if packet.qos > 0
end
else
# Wait for one packet to be available
packet = @read_queue.pop
puback_packet(packet) if packet.qos > 0
return packet
end
end | [
"def",
"get_packet",
"(",
"topic",
"=",
"nil",
")",
"# Subscribe to a topic, if an argument is given",
"subscribe",
"(",
"topic",
")",
"unless",
"topic",
".",
"nil?",
"if",
"block_given?",
"# Loop forever!",
"loop",
"do",
"packet",
"=",
"@read_queue",
".",
"pop",
"yield",
"(",
"packet",
")",
"puback_packet",
"(",
"packet",
")",
"if",
"packet",
".",
"qos",
">",
"0",
"end",
"else",
"# Wait for one packet to be available",
"packet",
"=",
"@read_queue",
".",
"pop",
"puback_packet",
"(",
"packet",
")",
"if",
"packet",
".",
"qos",
">",
"0",
"return",
"packet",
"end",
"end"
] | Return the next packet object received from the MQTT server.
An optional topic can be given to subscribe to.
The method either returns a single packet:
packet = client.get_packet
puts packet.topic
Or can be used with a block to keep processing messages:
client.get_packet('test') do |packet|
# Do stuff here
puts packet.topic
end | [
"Return",
"the",
"next",
"packet",
"object",
"received",
"from",
"the",
"MQTT",
"server",
".",
"An",
"optional",
"topic",
"can",
"be",
"given",
"to",
"subscribe",
"to",
"."
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/client.rb#L399-L416 | train |
njh/ruby-mqtt | lib/mqtt/client.rb | MQTT.Client.unsubscribe | def unsubscribe(*topics)
topics = topics.first if topics.is_a?(Enumerable) && topics.count == 1
packet = MQTT::Packet::Unsubscribe.new(
:topics => topics,
:id => next_packet_id
)
send_packet(packet)
end | ruby | def unsubscribe(*topics)
topics = topics.first if topics.is_a?(Enumerable) && topics.count == 1
packet = MQTT::Packet::Unsubscribe.new(
:topics => topics,
:id => next_packet_id
)
send_packet(packet)
end | [
"def",
"unsubscribe",
"(",
"*",
"topics",
")",
"topics",
"=",
"topics",
".",
"first",
"if",
"topics",
".",
"is_a?",
"(",
"Enumerable",
")",
"&&",
"topics",
".",
"count",
"==",
"1",
"packet",
"=",
"MQTT",
"::",
"Packet",
"::",
"Unsubscribe",
".",
"new",
"(",
":topics",
"=>",
"topics",
",",
":id",
"=>",
"next_packet_id",
")",
"send_packet",
"(",
"packet",
")",
"end"
] | Send a unsubscribe message for one or more topics on the MQTT server | [
"Send",
"a",
"unsubscribe",
"message",
"for",
"one",
"or",
"more",
"topics",
"on",
"the",
"MQTT",
"server"
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/client.rb#L434-L442 | train |
njh/ruby-mqtt | lib/mqtt/client.rb | MQTT.Client.receive_packet | def receive_packet
# Poll socket - is there data waiting?
result = IO.select([@socket], [], [], SELECT_TIMEOUT)
unless result.nil?
# Yes - read in the packet
packet = MQTT::Packet.read(@socket)
handle_packet packet
end
keep_alive!
# Pass exceptions up to parent thread
rescue Exception => exp
unless @socket.nil?
@socket.close
@socket = nil
end
Thread.current[:parent].raise(exp)
end | ruby | def receive_packet
# Poll socket - is there data waiting?
result = IO.select([@socket], [], [], SELECT_TIMEOUT)
unless result.nil?
# Yes - read in the packet
packet = MQTT::Packet.read(@socket)
handle_packet packet
end
keep_alive!
# Pass exceptions up to parent thread
rescue Exception => exp
unless @socket.nil?
@socket.close
@socket = nil
end
Thread.current[:parent].raise(exp)
end | [
"def",
"receive_packet",
"# Poll socket - is there data waiting?",
"result",
"=",
"IO",
".",
"select",
"(",
"[",
"@socket",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"SELECT_TIMEOUT",
")",
"unless",
"result",
".",
"nil?",
"# Yes - read in the packet",
"packet",
"=",
"MQTT",
"::",
"Packet",
".",
"read",
"(",
"@socket",
")",
"handle_packet",
"packet",
"end",
"keep_alive!",
"# Pass exceptions up to parent thread",
"rescue",
"Exception",
"=>",
"exp",
"unless",
"@socket",
".",
"nil?",
"@socket",
".",
"close",
"@socket",
"=",
"nil",
"end",
"Thread",
".",
"current",
"[",
":parent",
"]",
".",
"raise",
"(",
"exp",
")",
"end"
] | Try to read a packet from the server
Also sends keep-alive ping packets. | [
"Try",
"to",
"read",
"a",
"packet",
"from",
"the",
"server",
"Also",
"sends",
"keep",
"-",
"alive",
"ping",
"packets",
"."
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/client.rb#L448-L464 | train |
njh/ruby-mqtt | lib/mqtt/client.rb | MQTT.Client.receive_connack | def receive_connack
Timeout.timeout(@ack_timeout) do
packet = MQTT::Packet.read(@socket)
if packet.class != MQTT::Packet::Connack
raise MQTT::ProtocolException, "Response wasn't a connection acknowledgement: #{packet.class}"
end
# Check the return code
if packet.return_code != 0x00
# 3.2.2.3 If a server sends a CONNACK packet containing a non-zero
# return code it MUST then close the Network Connection
@socket.close
raise MQTT::ProtocolException, packet.return_msg
end
end
end | ruby | def receive_connack
Timeout.timeout(@ack_timeout) do
packet = MQTT::Packet.read(@socket)
if packet.class != MQTT::Packet::Connack
raise MQTT::ProtocolException, "Response wasn't a connection acknowledgement: #{packet.class}"
end
# Check the return code
if packet.return_code != 0x00
# 3.2.2.3 If a server sends a CONNACK packet containing a non-zero
# return code it MUST then close the Network Connection
@socket.close
raise MQTT::ProtocolException, packet.return_msg
end
end
end | [
"def",
"receive_connack",
"Timeout",
".",
"timeout",
"(",
"@ack_timeout",
")",
"do",
"packet",
"=",
"MQTT",
"::",
"Packet",
".",
"read",
"(",
"@socket",
")",
"if",
"packet",
".",
"class",
"!=",
"MQTT",
"::",
"Packet",
"::",
"Connack",
"raise",
"MQTT",
"::",
"ProtocolException",
",",
"\"Response wasn't a connection acknowledgement: #{packet.class}\"",
"end",
"# Check the return code",
"if",
"packet",
".",
"return_code",
"!=",
"0x00",
"# 3.2.2.3 If a server sends a CONNACK packet containing a non-zero",
"# return code it MUST then close the Network Connection",
"@socket",
".",
"close",
"raise",
"MQTT",
"::",
"ProtocolException",
",",
"packet",
".",
"return_msg",
"end",
"end",
"end"
] | Read and check a connection acknowledgement packet | [
"Read",
"and",
"check",
"a",
"connection",
"acknowledgement",
"packet"
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/client.rb#L499-L514 | train |
njh/ruby-mqtt | lib/mqtt/client.rb | MQTT.Client.send_packet | def send_packet(data)
# Raise exception if we aren't connected
raise MQTT::NotConnectedException unless connected?
# Only allow one thread to write to socket at a time
@write_semaphore.synchronize do
@socket.write(data.to_s)
end
end | ruby | def send_packet(data)
# Raise exception if we aren't connected
raise MQTT::NotConnectedException unless connected?
# Only allow one thread to write to socket at a time
@write_semaphore.synchronize do
@socket.write(data.to_s)
end
end | [
"def",
"send_packet",
"(",
"data",
")",
"# Raise exception if we aren't connected",
"raise",
"MQTT",
"::",
"NotConnectedException",
"unless",
"connected?",
"# Only allow one thread to write to socket at a time",
"@write_semaphore",
".",
"synchronize",
"do",
"@socket",
".",
"write",
"(",
"data",
".",
"to_s",
")",
"end",
"end"
] | Send a packet to server | [
"Send",
"a",
"packet",
"to",
"server"
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/client.rb#L517-L525 | train |
njh/ruby-mqtt | lib/mqtt/proxy.rb | MQTT.Proxy.run | def run
loop do
# Wait for a client to connect and then create a thread for it
Thread.new(@server.accept) do |client_socket|
logger.info "Accepted client: #{client_socket.peeraddr.join(':')}"
server_socket = TCPSocket.new(@server_host, @server_port)
begin
process_packets(client_socket, server_socket)
rescue Exception => exp
logger.error exp.to_s
end
logger.info "Disconnected: #{client_socket.peeraddr.join(':')}"
server_socket.close
client_socket.close
end
end
end | ruby | def run
loop do
# Wait for a client to connect and then create a thread for it
Thread.new(@server.accept) do |client_socket|
logger.info "Accepted client: #{client_socket.peeraddr.join(':')}"
server_socket = TCPSocket.new(@server_host, @server_port)
begin
process_packets(client_socket, server_socket)
rescue Exception => exp
logger.error exp.to_s
end
logger.info "Disconnected: #{client_socket.peeraddr.join(':')}"
server_socket.close
client_socket.close
end
end
end | [
"def",
"run",
"loop",
"do",
"# Wait for a client to connect and then create a thread for it",
"Thread",
".",
"new",
"(",
"@server",
".",
"accept",
")",
"do",
"|",
"client_socket",
"|",
"logger",
".",
"info",
"\"Accepted client: #{client_socket.peeraddr.join(':')}\"",
"server_socket",
"=",
"TCPSocket",
".",
"new",
"(",
"@server_host",
",",
"@server_port",
")",
"begin",
"process_packets",
"(",
"client_socket",
",",
"server_socket",
")",
"rescue",
"Exception",
"=>",
"exp",
"logger",
".",
"error",
"exp",
".",
"to_s",
"end",
"logger",
".",
"info",
"\"Disconnected: #{client_socket.peeraddr.join(':')}\"",
"server_socket",
".",
"close",
"client_socket",
".",
"close",
"end",
"end",
"end"
] | Create a new MQTT Proxy instance.
Possible argument keys:
:local_host Address to bind listening socket to.
:local_port Port to bind listening socket to.
:server_host Address of upstream server to send packets upstream to.
:server_port Port of upstream server to send packets upstream to.
:select_timeout Time in seconds before disconnecting a connection.
:logger Ruby Logger object to send informational messages to.
NOTE: be careful not to connect to yourself!
Start accepting connections and processing packets. | [
"Create",
"a",
"new",
"MQTT",
"Proxy",
"instance",
"."
] | 878639e85827aa25688e9c4ef1511d393549dcfa | https://github.com/njh/ruby-mqtt/blob/878639e85827aa25688e9c4ef1511d393549dcfa/lib/mqtt/proxy.rb#L64-L80 | train |
influxdata/influxdb-ruby | lib/influxdb/config.rb | InfluxDB.Config.configure_hosts! | def configure_hosts!(hosts)
@hosts_queue = Queue.new
Array(hosts).each do |host|
@hosts_queue.push(host)
end
end | ruby | def configure_hosts!(hosts)
@hosts_queue = Queue.new
Array(hosts).each do |host|
@hosts_queue.push(host)
end
end | [
"def",
"configure_hosts!",
"(",
"hosts",
")",
"@hosts_queue",
"=",
"Queue",
".",
"new",
"Array",
"(",
"hosts",
")",
".",
"each",
"do",
"|",
"host",
"|",
"@hosts_queue",
".",
"push",
"(",
"host",
")",
"end",
"end"
] | load the hosts into a Queue for thread safety | [
"load",
"the",
"hosts",
"into",
"a",
"Queue",
"for",
"thread",
"safety"
] | c4821e9897ca513601e04372feaab6e2096878ba | https://github.com/influxdata/influxdb-ruby/blob/c4821e9897ca513601e04372feaab6e2096878ba/lib/influxdb/config.rb#L127-L132 | train |
influxdata/influxdb-ruby | lib/influxdb/config.rb | InfluxDB.Config.opts_from_url | def opts_from_url(url)
url = URI.parse(url) unless url.is_a?(URI)
opts_from_non_params(url).merge opts_from_params(url.query)
rescue URI::InvalidURIError
{}
end | ruby | def opts_from_url(url)
url = URI.parse(url) unless url.is_a?(URI)
opts_from_non_params(url).merge opts_from_params(url.query)
rescue URI::InvalidURIError
{}
end | [
"def",
"opts_from_url",
"(",
"url",
")",
"url",
"=",
"URI",
".",
"parse",
"(",
"url",
")",
"unless",
"url",
".",
"is_a?",
"(",
"URI",
")",
"opts_from_non_params",
"(",
"url",
")",
".",
"merge",
"opts_from_params",
"(",
"url",
".",
"query",
")",
"rescue",
"URI",
"::",
"InvalidURIError",
"{",
"}",
"end"
] | merges URI options into opts | [
"merges",
"URI",
"options",
"into",
"opts"
] | c4821e9897ca513601e04372feaab6e2096878ba | https://github.com/influxdata/influxdb-ruby/blob/c4821e9897ca513601e04372feaab6e2096878ba/lib/influxdb/config.rb#L135-L140 | train |
bolshakov/fear | lib/fear/future.rb | Fear.Future.on_complete_match | def on_complete_match
promise.add_observer do |_time, try, _error|
Fear::Try.matcher { |m| yield(m) }.call_or_else(try, &:itself)
end
self
end | ruby | def on_complete_match
promise.add_observer do |_time, try, _error|
Fear::Try.matcher { |m| yield(m) }.call_or_else(try, &:itself)
end
self
end | [
"def",
"on_complete_match",
"promise",
".",
"add_observer",
"do",
"|",
"_time",
",",
"try",
",",
"_error",
"|",
"Fear",
"::",
"Try",
".",
"matcher",
"{",
"|",
"m",
"|",
"yield",
"(",
"m",
")",
"}",
".",
"call_or_else",
"(",
"try",
",",
":itself",
")",
"end",
"self",
"end"
] | When this future is completed match against result.
If the future has already been completed,
this will either be applied immediately or be scheduled asynchronously.
@yieldparam [Fear::TryPatternMatch]
@return [self]
@example
Fear.future { }.on_complete_match do |m|
m.success { |result| }
m.failure { |error| }
end | [
"When",
"this",
"future",
"is",
"completed",
"match",
"against",
"result",
"."
] | 3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e | https://github.com/bolshakov/fear/blob/3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e/lib/fear/future.rb#L186-L191 | train |
bolshakov/fear | lib/fear/future.rb | Fear.Future.transform | def transform(success, failure)
promise = Promise.new(@options)
on_complete_match do |m|
m.success { |value| promise.success(success.call(value)) }
m.failure { |error| promise.failure(failure.call(error)) }
end
promise.to_future
end | ruby | def transform(success, failure)
promise = Promise.new(@options)
on_complete_match do |m|
m.success { |value| promise.success(success.call(value)) }
m.failure { |error| promise.failure(failure.call(error)) }
end
promise.to_future
end | [
"def",
"transform",
"(",
"success",
",",
"failure",
")",
"promise",
"=",
"Promise",
".",
"new",
"(",
"@options",
")",
"on_complete_match",
"do",
"|",
"m",
"|",
"m",
".",
"success",
"{",
"|",
"value",
"|",
"promise",
".",
"success",
"(",
"success",
".",
"call",
"(",
"value",
")",
")",
"}",
"m",
".",
"failure",
"{",
"|",
"error",
"|",
"promise",
".",
"failure",
"(",
"failure",
".",
"call",
"(",
"error",
")",
")",
"}",
"end",
"promise",
".",
"to_future",
"end"
] | Creates a new future by applying the +success+ function to the successful
result of this future, or the +failure+ function to the failed result.
If there is any non-fatal error raised when +success+ or +failure+ is
applied, that error will be propagated to the resulting future.
@yieldparam success [#get] function that transforms a successful result of the
receiver into a successful result of the returned future
@yieldparam failure [#exception] function that transforms a failure of the
receiver into a failure of the returned future
@return [Fear::Future] a future that will be completed with the
transformed value
@example
Fear.future { open('http://example.com').read }
.transform(
->(value) { ... },
->(error) { ... },
) | [
"Creates",
"a",
"new",
"future",
"by",
"applying",
"the",
"+",
"success",
"+",
"function",
"to",
"the",
"successful",
"result",
"of",
"this",
"future",
"or",
"the",
"+",
"failure",
"+",
"function",
"to",
"the",
"failed",
"result",
".",
"If",
"there",
"is",
"any",
"non",
"-",
"fatal",
"error",
"raised",
"when",
"+",
"success",
"+",
"or",
"+",
"failure",
"+",
"is",
"applied",
"that",
"error",
"will",
"be",
"propagated",
"to",
"the",
"resulting",
"future",
"."
] | 3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e | https://github.com/bolshakov/fear/blob/3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e/lib/fear/future.rb#L249-L256 | train |
bolshakov/fear | lib/fear/future.rb | Fear.Future.map | def map(&block)
promise = Promise.new(@options)
on_complete do |try|
promise.complete!(try.map(&block))
end
promise.to_future
end | ruby | def map(&block)
promise = Promise.new(@options)
on_complete do |try|
promise.complete!(try.map(&block))
end
promise.to_future
end | [
"def",
"map",
"(",
"&",
"block",
")",
"promise",
"=",
"Promise",
".",
"new",
"(",
"@options",
")",
"on_complete",
"do",
"|",
"try",
"|",
"promise",
".",
"complete!",
"(",
"try",
".",
"map",
"(",
"block",
")",
")",
"end",
"promise",
".",
"to_future",
"end"
] | Creates a new future by applying a block to the successful result of
this future. If this future is completed with an error then the new
future will also contain this error.
@return [Fear::Future]
@example
future = Fear.future { 2 }
future.map { |v| v * 2 } #=> the same as Fear.future { 2 * 2 } | [
"Creates",
"a",
"new",
"future",
"by",
"applying",
"a",
"block",
"to",
"the",
"successful",
"result",
"of",
"this",
"future",
".",
"If",
"this",
"future",
"is",
"completed",
"with",
"an",
"error",
"then",
"the",
"new",
"future",
"will",
"also",
"contain",
"this",
"error",
"."
] | 3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e | https://github.com/bolshakov/fear/blob/3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e/lib/fear/future.rb#L268-L275 | train |
bolshakov/fear | lib/fear/future.rb | Fear.Future.flat_map | def flat_map # rubocop: disable Metrics/MethodLength
promise = Promise.new(@options)
on_complete_match do |m|
m.case(Fear::Failure) { |failure| promise.complete!(failure) }
m.success do |value|
begin
yield(value).on_complete { |callback_result| promise.complete!(callback_result) }
rescue StandardError => error
promise.failure!(error)
end
end
end
promise.to_future
end | ruby | def flat_map # rubocop: disable Metrics/MethodLength
promise = Promise.new(@options)
on_complete_match do |m|
m.case(Fear::Failure) { |failure| promise.complete!(failure) }
m.success do |value|
begin
yield(value).on_complete { |callback_result| promise.complete!(callback_result) }
rescue StandardError => error
promise.failure!(error)
end
end
end
promise.to_future
end | [
"def",
"flat_map",
"# rubocop: disable Metrics/MethodLength",
"promise",
"=",
"Promise",
".",
"new",
"(",
"@options",
")",
"on_complete_match",
"do",
"|",
"m",
"|",
"m",
".",
"case",
"(",
"Fear",
"::",
"Failure",
")",
"{",
"|",
"failure",
"|",
"promise",
".",
"complete!",
"(",
"failure",
")",
"}",
"m",
".",
"success",
"do",
"|",
"value",
"|",
"begin",
"yield",
"(",
"value",
")",
".",
"on_complete",
"{",
"|",
"callback_result",
"|",
"promise",
".",
"complete!",
"(",
"callback_result",
")",
"}",
"rescue",
"StandardError",
"=>",
"error",
"promise",
".",
"failure!",
"(",
"error",
")",
"end",
"end",
"end",
"promise",
".",
"to_future",
"end"
] | Creates a new future by applying a block to the successful result of
this future, and returns the result of the function as the new future.
If this future is completed with an exception then the new future will
also contain this exception.
@yieldparam [any]
@return [Fear::Future]
@example
f1 = Fear.future { 5 }
f2 = Fear.future { 3 }
f1.flat_map do |v1|
f1.map do |v2|
v2 * v1
end
end | [
"Creates",
"a",
"new",
"future",
"by",
"applying",
"a",
"block",
"to",
"the",
"successful",
"result",
"of",
"this",
"future",
"and",
"returns",
"the",
"result",
"of",
"the",
"function",
"as",
"the",
"new",
"future",
".",
"If",
"this",
"future",
"is",
"completed",
"with",
"an",
"exception",
"then",
"the",
"new",
"future",
"will",
"also",
"contain",
"this",
"exception",
"."
] | 3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e | https://github.com/bolshakov/fear/blob/3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e/lib/fear/future.rb#L294-L307 | train |
bolshakov/fear | lib/fear/future.rb | Fear.Future.zip | def zip(other) # rubocop: disable Metrics/MethodLength
promise = Promise.new(@options)
on_complete_match do |m|
m.success do |value|
other.on_complete do |other_try|
promise.complete!(other_try.map { |other_value| [value, other_value] })
end
end
m.failure do |error|
promise.failure!(error)
end
end
promise.to_future
end | ruby | def zip(other) # rubocop: disable Metrics/MethodLength
promise = Promise.new(@options)
on_complete_match do |m|
m.success do |value|
other.on_complete do |other_try|
promise.complete!(other_try.map { |other_value| [value, other_value] })
end
end
m.failure do |error|
promise.failure!(error)
end
end
promise.to_future
end | [
"def",
"zip",
"(",
"other",
")",
"# rubocop: disable Metrics/MethodLength",
"promise",
"=",
"Promise",
".",
"new",
"(",
"@options",
")",
"on_complete_match",
"do",
"|",
"m",
"|",
"m",
".",
"success",
"do",
"|",
"value",
"|",
"other",
".",
"on_complete",
"do",
"|",
"other_try",
"|",
"promise",
".",
"complete!",
"(",
"other_try",
".",
"map",
"{",
"|",
"other_value",
"|",
"[",
"value",
",",
"other_value",
"]",
"}",
")",
"end",
"end",
"m",
".",
"failure",
"do",
"|",
"error",
"|",
"promise",
".",
"failure!",
"(",
"error",
")",
"end",
"end",
"promise",
".",
"to_future",
"end"
] | Zips the values of +self+ and +other+ future, and creates
a new future holding the array of their results.
If +self+ future fails, the resulting future is failed
with the error stored in +self+.
Otherwise, if +other+ future fails, the resulting future is failed
with the error stored in +other+.
@param other [Fear::Future]
@return [Fear::Future]
@example
future1 = Fear.future { call_service1 }
future1 = Fear.future { call_service2 }
future1.zip(future2) #=> returns the same result as Fear.future { [call_service1, call_service2] },
# but it performs two calls asynchronously | [
"Zips",
"the",
"values",
"of",
"+",
"self",
"+",
"and",
"+",
"other",
"+",
"future",
"and",
"creates",
"a",
"new",
"future",
"holding",
"the",
"array",
"of",
"their",
"results",
"."
] | 3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e | https://github.com/bolshakov/fear/blob/3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e/lib/fear/future.rb#L376-L390 | train |
bolshakov/fear | lib/fear/future.rb | Fear.Future.fallback_to | def fallback_to(fallback)
promise = Promise.new(@options)
on_complete_match do |m|
m.success { |value| promise.complete!(value) }
m.failure do |error|
fallback.on_complete_match do |m2|
m2.success { |value| promise.complete!(value) }
m2.failure { promise.failure!(error) }
end
end
end
promise.to_future
end | ruby | def fallback_to(fallback)
promise = Promise.new(@options)
on_complete_match do |m|
m.success { |value| promise.complete!(value) }
m.failure do |error|
fallback.on_complete_match do |m2|
m2.success { |value| promise.complete!(value) }
m2.failure { promise.failure!(error) }
end
end
end
promise.to_future
end | [
"def",
"fallback_to",
"(",
"fallback",
")",
"promise",
"=",
"Promise",
".",
"new",
"(",
"@options",
")",
"on_complete_match",
"do",
"|",
"m",
"|",
"m",
".",
"success",
"{",
"|",
"value",
"|",
"promise",
".",
"complete!",
"(",
"value",
")",
"}",
"m",
".",
"failure",
"do",
"|",
"error",
"|",
"fallback",
".",
"on_complete_match",
"do",
"|",
"m2",
"|",
"m2",
".",
"success",
"{",
"|",
"value",
"|",
"promise",
".",
"complete!",
"(",
"value",
")",
"}",
"m2",
".",
"failure",
"{",
"promise",
".",
"failure!",
"(",
"error",
")",
"}",
"end",
"end",
"end",
"promise",
".",
"to_future",
"end"
] | Creates a new future which holds the result of +self+ future if it
was completed successfully, or, if not, the result of the +fallback+
future if +fallback+ is completed successfully.
If both futures are failed, the resulting future holds the error
object of the first future.
@param fallback [Fear::Future]
@return [Fear::Future]
@example
f = Fear.future { fail 'error' }
g = Fear.future { 5 }
f.fallback_to(g) # evaluates to 5
rubocop: disable Metrics/MethodLength | [
"Creates",
"a",
"new",
"future",
"which",
"holds",
"the",
"result",
"of",
"+",
"self",
"+",
"future",
"if",
"it",
"was",
"completed",
"successfully",
"or",
"if",
"not",
"the",
"result",
"of",
"the",
"+",
"fallback",
"+",
"future",
"if",
"+",
"fallback",
"+",
"is",
"completed",
"successfully",
".",
"If",
"both",
"futures",
"are",
"failed",
"the",
"resulting",
"future",
"holds",
"the",
"error",
"object",
"of",
"the",
"first",
"future",
"."
] | 3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e | https://github.com/bolshakov/fear/blob/3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e/lib/fear/future.rb#L407-L420 | train |
bolshakov/fear | lib/fear/option_pattern_match.rb | Fear.OptionPatternMatch.some | def some(*conditions, &effect)
branch = Fear.case(Fear::Some, &GET_METHOD).and_then(Fear.case(*conditions, &effect))
or_else(branch)
end | ruby | def some(*conditions, &effect)
branch = Fear.case(Fear::Some, &GET_METHOD).and_then(Fear.case(*conditions, &effect))
or_else(branch)
end | [
"def",
"some",
"(",
"*",
"conditions",
",",
"&",
"effect",
")",
"branch",
"=",
"Fear",
".",
"case",
"(",
"Fear",
"::",
"Some",
",",
"GET_METHOD",
")",
".",
"and_then",
"(",
"Fear",
".",
"case",
"(",
"conditions",
",",
"effect",
")",
")",
"or_else",
"(",
"branch",
")",
"end"
] | Match against Some
@param conditions [<#==>]
@return [Fear::OptionPatternMatch] | [
"Match",
"against",
"Some"
] | 3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e | https://github.com/bolshakov/fear/blob/3e7fbee20df69f9bd5f4ed8723bdcecf7605dd4e/lib/fear/option_pattern_match.rb#L31-L34 | train |
opoloo/lines-engine | app/models/lines/article.rb | Lines.Article.used_images | def used_images
result = content.scan(/!\[.*\]\(.*\/image\/(\d.*)\/.*\)/)
image_ids = result.nil? ? nil : result.map{ |i| i[0].to_i }.uniq
image_ids
end | ruby | def used_images
result = content.scan(/!\[.*\]\(.*\/image\/(\d.*)\/.*\)/)
image_ids = result.nil? ? nil : result.map{ |i| i[0].to_i }.uniq
image_ids
end | [
"def",
"used_images",
"result",
"=",
"content",
".",
"scan",
"(",
"/",
"\\[",
"\\]",
"\\(",
"\\/",
"\\/",
"\\d",
"\\/",
"\\)",
"/",
")",
"image_ids",
"=",
"result",
".",
"nil?",
"?",
"nil",
":",
"result",
".",
"map",
"{",
"|",
"i",
"|",
"i",
"[",
"0",
"]",
".",
"to_i",
"}",
".",
"uniq",
"image_ids",
"end"
] | Returns array of images used in content | [
"Returns",
"array",
"of",
"images",
"used",
"in",
"content"
] | 9ae0525e882a9c323558353ce1941c50e8bcfc67 | https://github.com/opoloo/lines-engine/blob/9ae0525e882a9c323558353ce1941c50e8bcfc67/app/models/lines/article.rb#L58-L62 | train |
opoloo/lines-engine | app/models/lines/article.rb | Lines.Article.update_used_images | def update_used_images
ActionController::Base.new.expire_fragment(self)
image_ids = self.used_images
if !image_ids.nil?
Picture.where(id: image_ids).each do |picture|
picture.update_attributes(article_id: self.id)
end
end
end | ruby | def update_used_images
ActionController::Base.new.expire_fragment(self)
image_ids = self.used_images
if !image_ids.nil?
Picture.where(id: image_ids).each do |picture|
picture.update_attributes(article_id: self.id)
end
end
end | [
"def",
"update_used_images",
"ActionController",
"::",
"Base",
".",
"new",
".",
"expire_fragment",
"(",
"self",
")",
"image_ids",
"=",
"self",
".",
"used_images",
"if",
"!",
"image_ids",
".",
"nil?",
"Picture",
".",
"where",
"(",
"id",
":",
"image_ids",
")",
".",
"each",
"do",
"|",
"picture",
"|",
"picture",
".",
"update_attributes",
"(",
"article_id",
":",
"self",
".",
"id",
")",
"end",
"end",
"end"
] | Finds images used in an articles content and associates each
image to the blog article | [
"Finds",
"images",
"used",
"in",
"an",
"articles",
"content",
"and",
"associates",
"each",
"image",
"to",
"the",
"blog",
"article"
] | 9ae0525e882a9c323558353ce1941c50e8bcfc67 | https://github.com/opoloo/lines-engine/blob/9ae0525e882a9c323558353ce1941c50e8bcfc67/app/models/lines/article.rb#L83-L91 | train |
opoloo/lines-engine | app/models/lines/article.rb | Lines.Article.refresh_sitemap | def refresh_sitemap
if self.published
if Rails.env == 'production' && ENV["CONFIG_FILE"]
SitemapGenerator::Interpreter.run(config_file: ENV["CONFIG_FILE"])
SitemapGenerator::Sitemap.ping_search_engines
end
end
end | ruby | def refresh_sitemap
if self.published
if Rails.env == 'production' && ENV["CONFIG_FILE"]
SitemapGenerator::Interpreter.run(config_file: ENV["CONFIG_FILE"])
SitemapGenerator::Sitemap.ping_search_engines
end
end
end | [
"def",
"refresh_sitemap",
"if",
"self",
".",
"published",
"if",
"Rails",
".",
"env",
"==",
"'production'",
"&&",
"ENV",
"[",
"\"CONFIG_FILE\"",
"]",
"SitemapGenerator",
"::",
"Interpreter",
".",
"run",
"(",
"config_file",
":",
"ENV",
"[",
"\"CONFIG_FILE\"",
"]",
")",
"SitemapGenerator",
"::",
"Sitemap",
".",
"ping_search_engines",
"end",
"end",
"end"
] | Refreshes the sitemap and pings the search engines | [
"Refreshes",
"the",
"sitemap",
"and",
"pings",
"the",
"search",
"engines"
] | 9ae0525e882a9c323558353ce1941c50e8bcfc67 | https://github.com/opoloo/lines-engine/blob/9ae0525e882a9c323558353ce1941c50e8bcfc67/app/models/lines/article.rb#L94-L101 | train |
opoloo/lines-engine | app/controllers/lines/articles_controller.rb | Lines.ArticlesController.index | def index
respond_to do |format|
format.html {
@first_page = (params[:page] and params[:page].to_i > 0) ? false : true
if params[:tag]
@articles = Lines::Article.published.tagged_with(params[:tag]).page(params[:page].to_i)
else
@articles = Lines::Article.published.page(params[:page].to_i).padding(1)
end
if @articles.first_page?
if @first_article = Article.published.first
@first_article.teaser = nil unless @first_article.teaser.present?
end
end
set_meta_tags title: SITE_TITLE,
description: CONFIG[:meta_description],
keywords: KEYWORDS,
open_graph: { title: SITE_TITLE,
type: 'website',
url: articles_url,
site_name: SITE_TITLE,
image: CONFIG[:og_logo]
}
}
format.atom{
@articles = Lines::Article.published
}
end
end | ruby | def index
respond_to do |format|
format.html {
@first_page = (params[:page] and params[:page].to_i > 0) ? false : true
if params[:tag]
@articles = Lines::Article.published.tagged_with(params[:tag]).page(params[:page].to_i)
else
@articles = Lines::Article.published.page(params[:page].to_i).padding(1)
end
if @articles.first_page?
if @first_article = Article.published.first
@first_article.teaser = nil unless @first_article.teaser.present?
end
end
set_meta_tags title: SITE_TITLE,
description: CONFIG[:meta_description],
keywords: KEYWORDS,
open_graph: { title: SITE_TITLE,
type: 'website',
url: articles_url,
site_name: SITE_TITLE,
image: CONFIG[:og_logo]
}
}
format.atom{
@articles = Lines::Article.published
}
end
end | [
"def",
"index",
"respond_to",
"do",
"|",
"format",
"|",
"format",
".",
"html",
"{",
"@first_page",
"=",
"(",
"params",
"[",
":page",
"]",
"and",
"params",
"[",
":page",
"]",
".",
"to_i",
">",
"0",
")",
"?",
"false",
":",
"true",
"if",
"params",
"[",
":tag",
"]",
"@articles",
"=",
"Lines",
"::",
"Article",
".",
"published",
".",
"tagged_with",
"(",
"params",
"[",
":tag",
"]",
")",
".",
"page",
"(",
"params",
"[",
":page",
"]",
".",
"to_i",
")",
"else",
"@articles",
"=",
"Lines",
"::",
"Article",
".",
"published",
".",
"page",
"(",
"params",
"[",
":page",
"]",
".",
"to_i",
")",
".",
"padding",
"(",
"1",
")",
"end",
"if",
"@articles",
".",
"first_page?",
"if",
"@first_article",
"=",
"Article",
".",
"published",
".",
"first",
"@first_article",
".",
"teaser",
"=",
"nil",
"unless",
"@first_article",
".",
"teaser",
".",
"present?",
"end",
"end",
"set_meta_tags",
"title",
":",
"SITE_TITLE",
",",
"description",
":",
"CONFIG",
"[",
":meta_description",
"]",
",",
"keywords",
":",
"KEYWORDS",
",",
"open_graph",
":",
"{",
"title",
":",
"SITE_TITLE",
",",
"type",
":",
"'website'",
",",
"url",
":",
"articles_url",
",",
"site_name",
":",
"SITE_TITLE",
",",
"image",
":",
"CONFIG",
"[",
":og_logo",
"]",
"}",
"}",
"format",
".",
"atom",
"{",
"@articles",
"=",
"Lines",
"::",
"Article",
".",
"published",
"}",
"end",
"end"
] | Lists all published articles.
Responds to html and atom | [
"Lists",
"all",
"published",
"articles",
".",
"Responds",
"to",
"html",
"and",
"atom"
] | 9ae0525e882a9c323558353ce1941c50e8bcfc67 | https://github.com/opoloo/lines-engine/blob/9ae0525e882a9c323558353ce1941c50e8bcfc67/app/controllers/lines/articles_controller.rb#L16-L47 | train |
opoloo/lines-engine | app/controllers/lines/articles_controller.rb | Lines.ArticlesController.show | def show
@first_page = true
@article = Lines::Article.published.find(params[:id])
@article.teaser = nil unless @article.teaser.present?
meta_tags = { title: @article.title,
type: 'article',
url: url_for(@article),
site_name: SITE_TITLE,
}
meta_tags[:image] = CONFIG[:host] + @article.image_url if @article.image_url.present?
set_meta_tags title: @article.title,
keywords: KEYWORDS + @article.tag_list.to_s,
open_graph: meta_tags
if request.path != article_path(@article)
return redirect_to @article, status: :moved_permanently
end
@related_articles = Lines::Article.published.where('id != ?', @article.id).order('').limit(2)
end | ruby | def show
@first_page = true
@article = Lines::Article.published.find(params[:id])
@article.teaser = nil unless @article.teaser.present?
meta_tags = { title: @article.title,
type: 'article',
url: url_for(@article),
site_name: SITE_TITLE,
}
meta_tags[:image] = CONFIG[:host] + @article.image_url if @article.image_url.present?
set_meta_tags title: @article.title,
keywords: KEYWORDS + @article.tag_list.to_s,
open_graph: meta_tags
if request.path != article_path(@article)
return redirect_to @article, status: :moved_permanently
end
@related_articles = Lines::Article.published.where('id != ?', @article.id).order('').limit(2)
end | [
"def",
"show",
"@first_page",
"=",
"true",
"@article",
"=",
"Lines",
"::",
"Article",
".",
"published",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@article",
".",
"teaser",
"=",
"nil",
"unless",
"@article",
".",
"teaser",
".",
"present?",
"meta_tags",
"=",
"{",
"title",
":",
"@article",
".",
"title",
",",
"type",
":",
"'article'",
",",
"url",
":",
"url_for",
"(",
"@article",
")",
",",
"site_name",
":",
"SITE_TITLE",
",",
"}",
"meta_tags",
"[",
":image",
"]",
"=",
"CONFIG",
"[",
":host",
"]",
"+",
"@article",
".",
"image_url",
"if",
"@article",
".",
"image_url",
".",
"present?",
"set_meta_tags",
"title",
":",
"@article",
".",
"title",
",",
"keywords",
":",
"KEYWORDS",
"+",
"@article",
".",
"tag_list",
".",
"to_s",
",",
"open_graph",
":",
"meta_tags",
"if",
"request",
".",
"path",
"!=",
"article_path",
"(",
"@article",
")",
"return",
"redirect_to",
"@article",
",",
"status",
":",
":moved_permanently",
"end",
"@related_articles",
"=",
"Lines",
"::",
"Article",
".",
"published",
".",
"where",
"(",
"'id != ?'",
",",
"@article",
".",
"id",
")",
".",
"order",
"(",
"''",
")",
".",
"limit",
"(",
"2",
")",
"end"
] | Shows specific article | [
"Shows",
"specific",
"article"
] | 9ae0525e882a9c323558353ce1941c50e8bcfc67 | https://github.com/opoloo/lines-engine/blob/9ae0525e882a9c323558353ce1941c50e8bcfc67/app/controllers/lines/articles_controller.rb#L50-L68 | train |
opoloo/lines-engine | app/helpers/lines/application_helper.rb | Lines.ApplicationHelper.render_teaser | def render_teaser(article, article_counter=0)
if article_counter < 0
teaser = article.teaser && article.teaser.present? ? markdown(article.teaser) : nil
else
teaser = article.teaser && article.teaser.present? ? format_code(article.teaser) : format_code(article.content)
end
teaser
end | ruby | def render_teaser(article, article_counter=0)
if article_counter < 0
teaser = article.teaser && article.teaser.present? ? markdown(article.teaser) : nil
else
teaser = article.teaser && article.teaser.present? ? format_code(article.teaser) : format_code(article.content)
end
teaser
end | [
"def",
"render_teaser",
"(",
"article",
",",
"article_counter",
"=",
"0",
")",
"if",
"article_counter",
"<",
"0",
"teaser",
"=",
"article",
".",
"teaser",
"&&",
"article",
".",
"teaser",
".",
"present?",
"?",
"markdown",
"(",
"article",
".",
"teaser",
")",
":",
"nil",
"else",
"teaser",
"=",
"article",
".",
"teaser",
"&&",
"article",
".",
"teaser",
".",
"present?",
"?",
"format_code",
"(",
"article",
".",
"teaser",
")",
":",
"format_code",
"(",
"article",
".",
"content",
")",
"end",
"teaser",
"end"
] | Renders the teaser for an article. | [
"Renders",
"the",
"teaser",
"for",
"an",
"article",
"."
] | 9ae0525e882a9c323558353ce1941c50e8bcfc67 | https://github.com/opoloo/lines-engine/blob/9ae0525e882a9c323558353ce1941c50e8bcfc67/app/helpers/lines/application_helper.rb#L9-L16 | train |
opoloo/lines-engine | app/helpers/lines/application_helper.rb | Lines.ApplicationHelper.markdown | def markdown(text)
renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: false, with_toc_data: false)
options = {
autolink: true,
no_intra_emphasis: true,
fenced_code_blocks: true,
lax_html_blocks: true,
tables: true,
strikethrough: true,
superscript: true,
xhtml: true
}
Redcarpet::Markdown.new(renderer, options).render(text).html_safe
end | ruby | def markdown(text)
renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: false, with_toc_data: false)
options = {
autolink: true,
no_intra_emphasis: true,
fenced_code_blocks: true,
lax_html_blocks: true,
tables: true,
strikethrough: true,
superscript: true,
xhtml: true
}
Redcarpet::Markdown.new(renderer, options).render(text).html_safe
end | [
"def",
"markdown",
"(",
"text",
")",
"renderer",
"=",
"HTMLwithPygments",
".",
"new",
"(",
"hard_wrap",
":",
"true",
",",
"filter_html",
":",
"false",
",",
"with_toc_data",
":",
"false",
")",
"options",
"=",
"{",
"autolink",
":",
"true",
",",
"no_intra_emphasis",
":",
"true",
",",
"fenced_code_blocks",
":",
"true",
",",
"lax_html_blocks",
":",
"true",
",",
"tables",
":",
"true",
",",
"strikethrough",
":",
"true",
",",
"superscript",
":",
"true",
",",
"xhtml",
":",
"true",
"}",
"Redcarpet",
"::",
"Markdown",
".",
"new",
"(",
"renderer",
",",
"options",
")",
".",
"render",
"(",
"text",
")",
".",
"html_safe",
"end"
] | Returns formatted and highlighted code fragments | [
"Returns",
"formatted",
"and",
"highlighted",
"code",
"fragments"
] | 9ae0525e882a9c323558353ce1941c50e8bcfc67 | https://github.com/opoloo/lines-engine/blob/9ae0525e882a9c323558353ce1941c50e8bcfc67/app/helpers/lines/application_helper.rb#L33-L46 | train |
opoloo/lines-engine | app/helpers/lines/application_helper.rb | Lines.ApplicationHelper.nav_link | def nav_link(link_text, link_path)
recognized = Rails.application.routes.recognize_path(link_path)
class_name = recognized[:controller] == params[:controller] ? 'active' : ''
content_tag(:li, class: class_name) do
link_to link_text, link_path
end
end | ruby | def nav_link(link_text, link_path)
recognized = Rails.application.routes.recognize_path(link_path)
class_name = recognized[:controller] == params[:controller] ? 'active' : ''
content_tag(:li, class: class_name) do
link_to link_text, link_path
end
end | [
"def",
"nav_link",
"(",
"link_text",
",",
"link_path",
")",
"recognized",
"=",
"Rails",
".",
"application",
".",
"routes",
".",
"recognize_path",
"(",
"link_path",
")",
"class_name",
"=",
"recognized",
"[",
":controller",
"]",
"==",
"params",
"[",
":controller",
"]",
"?",
"'active'",
":",
"''",
"content_tag",
"(",
":li",
",",
"class",
":",
"class_name",
")",
"do",
"link_to",
"link_text",
",",
"link_path",
"end",
"end"
] | Returns links in active or inactive state for highlighting current page | [
"Returns",
"links",
"in",
"active",
"or",
"inactive",
"state",
"for",
"highlighting",
"current",
"page"
] | 9ae0525e882a9c323558353ce1941c50e8bcfc67 | https://github.com/opoloo/lines-engine/blob/9ae0525e882a9c323558353ce1941c50e8bcfc67/app/helpers/lines/application_helper.rb#L49-L55 | train |
opoloo/lines-engine | app/helpers/lines/application_helper.rb | Lines.ApplicationHelper.display_article_authors | def display_article_authors(article, with_info=false)
authors = article.authors.map{|author| author.gplus_profile.blank? ? author.name : link_to(author.name, author.gplus_profile)}.to_sentence(two_words_connector: " & ", last_word_connector: " & ").html_safe
if with_info
authors += (" — " + article.authors.map{|author| content_tag(:span, "#{author.description}", class: 'author_description') }.join(" — ")).html_safe
end
authors
end | ruby | def display_article_authors(article, with_info=false)
authors = article.authors.map{|author| author.gplus_profile.blank? ? author.name : link_to(author.name, author.gplus_profile)}.to_sentence(two_words_connector: " & ", last_word_connector: " & ").html_safe
if with_info
authors += (" — " + article.authors.map{|author| content_tag(:span, "#{author.description}", class: 'author_description') }.join(" — ")).html_safe
end
authors
end | [
"def",
"display_article_authors",
"(",
"article",
",",
"with_info",
"=",
"false",
")",
"authors",
"=",
"article",
".",
"authors",
".",
"map",
"{",
"|",
"author",
"|",
"author",
".",
"gplus_profile",
".",
"blank?",
"?",
"author",
".",
"name",
":",
"link_to",
"(",
"author",
".",
"name",
",",
"author",
".",
"gplus_profile",
")",
"}",
".",
"to_sentence",
"(",
"two_words_connector",
":",
"\" & \"",
",",
"last_word_connector",
":",
"\" & \"",
")",
".",
"html_safe",
"if",
"with_info",
"authors",
"+=",
"(",
"\" — \" +",
"a",
"ticle.a",
"u",
"thors.m",
"a",
"p{|",
"a",
"u",
"thor| ",
"c",
"ntent_tag(:",
"s",
"pan, ",
"\"",
"{author.description}\", ",
"c",
"ass: ",
"'",
"uthor_description') ",
"}",
"j",
"o",
"in(\"",
" ",
"— \")).h",
"t",
"m",
"l",
"_safe",
"end",
"authors",
"end"
] | Returns HTML with all authors of an article | [
"Returns",
"HTML",
"with",
"all",
"authors",
"of",
"an",
"article"
] | 9ae0525e882a9c323558353ce1941c50e8bcfc67 | https://github.com/opoloo/lines-engine/blob/9ae0525e882a9c323558353ce1941c50e8bcfc67/app/helpers/lines/application_helper.rb#L58-L64 | train |
opoloo/lines-engine | app/helpers/lines/application_helper.rb | Lines.ApplicationHelper.render_navbar | def render_navbar(&block)
action_link = get_action_link
if !action_link
action_link = CONFIG[:title_short]
end
html = content_tag(:div, id: 'navbar') do
content_tag(:div, class: 'navbar-inner') do
if current_lines_user
content_tag(:span, class: 'buttons', &block) + "<div class='btn-menu'><div class='stripes'></div></div>".html_safe +
"<div class='submenu'>
<div class='submenu-inner'>
<ul>
<li>#{link_to("Dashboard", admin_articles_path)}</li>
<li>#{link_to(t('activerecord.models.lines/author', count: 2).html_safe, admin_authors_path)}</li>
</ul>
<ul>
<li class='small'>#{t('lines.logged_in_as').html_safe} #{current_lines_user.email}</li>
<li>#{link_to(t('lines.buttons.logout').html_safe, logout_path)}</li>
</ul>
<ul>
<li>#{link_to(t('lines.buttons.formating_help').html_safe, "#", class: "btn-cheatsheet")}</li>
<li>#{link_to(t('lines.buttons.about').html_safe, "http://lines.opoloo.com")}</li>
</ul>
</div>
</div>".html_safe
else
content_tag(:span, link_to('', lines.root_path), class: 'backlink') + content_tag(:span, action_link, class: 'actionlink')
end
end
end
html
end | ruby | def render_navbar(&block)
action_link = get_action_link
if !action_link
action_link = CONFIG[:title_short]
end
html = content_tag(:div, id: 'navbar') do
content_tag(:div, class: 'navbar-inner') do
if current_lines_user
content_tag(:span, class: 'buttons', &block) + "<div class='btn-menu'><div class='stripes'></div></div>".html_safe +
"<div class='submenu'>
<div class='submenu-inner'>
<ul>
<li>#{link_to("Dashboard", admin_articles_path)}</li>
<li>#{link_to(t('activerecord.models.lines/author', count: 2).html_safe, admin_authors_path)}</li>
</ul>
<ul>
<li class='small'>#{t('lines.logged_in_as').html_safe} #{current_lines_user.email}</li>
<li>#{link_to(t('lines.buttons.logout').html_safe, logout_path)}</li>
</ul>
<ul>
<li>#{link_to(t('lines.buttons.formating_help').html_safe, "#", class: "btn-cheatsheet")}</li>
<li>#{link_to(t('lines.buttons.about').html_safe, "http://lines.opoloo.com")}</li>
</ul>
</div>
</div>".html_safe
else
content_tag(:span, link_to('', lines.root_path), class: 'backlink') + content_tag(:span, action_link, class: 'actionlink')
end
end
end
html
end | [
"def",
"render_navbar",
"(",
"&",
"block",
")",
"action_link",
"=",
"get_action_link",
"if",
"!",
"action_link",
"action_link",
"=",
"CONFIG",
"[",
":title_short",
"]",
"end",
"html",
"=",
"content_tag",
"(",
":div",
",",
"id",
":",
"'navbar'",
")",
"do",
"content_tag",
"(",
":div",
",",
"class",
":",
"'navbar-inner'",
")",
"do",
"if",
"current_lines_user",
"content_tag",
"(",
":span",
",",
"class",
":",
"'buttons'",
",",
"block",
")",
"+",
"\"<div class='btn-menu'><div class='stripes'></div></div>\"",
".",
"html_safe",
"+",
"\"<div class='submenu'>\n <div class='submenu-inner'>\n <ul>\n <li>#{link_to(\"Dashboard\", admin_articles_path)}</li>\n <li>#{link_to(t('activerecord.models.lines/author', count: 2).html_safe, admin_authors_path)}</li>\n </ul>\n <ul>\n <li class='small'>#{t('lines.logged_in_as').html_safe} #{current_lines_user.email}</li>\n <li>#{link_to(t('lines.buttons.logout').html_safe, logout_path)}</li>\n </ul>\n <ul>\n <li>#{link_to(t('lines.buttons.formating_help').html_safe, \"#\", class: \"btn-cheatsheet\")}</li>\n <li>#{link_to(t('lines.buttons.about').html_safe, \"http://lines.opoloo.com\")}</li>\n </ul>\n </div>\n </div>\"",
".",
"html_safe",
"else",
"content_tag",
"(",
":span",
",",
"link_to",
"(",
"''",
",",
"lines",
".",
"root_path",
")",
",",
"class",
":",
"'backlink'",
")",
"+",
"content_tag",
"(",
":span",
",",
"action_link",
",",
"class",
":",
"'actionlink'",
")",
"end",
"end",
"end",
"html",
"end"
] | Renders the navigation bar for logged in users | [
"Renders",
"the",
"navigation",
"bar",
"for",
"logged",
"in",
"users"
] | 9ae0525e882a9c323558353ce1941c50e8bcfc67 | https://github.com/opoloo/lines-engine/blob/9ae0525e882a9c323558353ce1941c50e8bcfc67/app/helpers/lines/application_helper.rb#L67-L98 | train |
opoloo/lines-engine | app/helpers/lines/application_helper.rb | Lines.ApplicationHelper.get_action_link | def get_action_link
if controller_path == 'admin/articles'
case action_name
when 'index' then t('lines/buttons/all_articles').html_safe
when 'new' then t('lines/buttons/new_article').html_safe
when 'edit' then t('lines/buttons/edit_article').html_safe
when 'show' then t('lines/buttons/preview').html_safe
end
elsif controller_path == 'admin/authors'
case action_name
when 'index' then t('lines/buttons/all_authors').html_safe
when 'new' then t('lines/buttons/new_author').html_safe
when 'edit' then t('lines/buttons/edit_author').html_safe
when 'show' then t('lines/buttons/author').html_safe
end
end
end | ruby | def get_action_link
if controller_path == 'admin/articles'
case action_name
when 'index' then t('lines/buttons/all_articles').html_safe
when 'new' then t('lines/buttons/new_article').html_safe
when 'edit' then t('lines/buttons/edit_article').html_safe
when 'show' then t('lines/buttons/preview').html_safe
end
elsif controller_path == 'admin/authors'
case action_name
when 'index' then t('lines/buttons/all_authors').html_safe
when 'new' then t('lines/buttons/new_author').html_safe
when 'edit' then t('lines/buttons/edit_author').html_safe
when 'show' then t('lines/buttons/author').html_safe
end
end
end | [
"def",
"get_action_link",
"if",
"controller_path",
"==",
"'admin/articles'",
"case",
"action_name",
"when",
"'index'",
"then",
"t",
"(",
"'lines/buttons/all_articles'",
")",
".",
"html_safe",
"when",
"'new'",
"then",
"t",
"(",
"'lines/buttons/new_article'",
")",
".",
"html_safe",
"when",
"'edit'",
"then",
"t",
"(",
"'lines/buttons/edit_article'",
")",
".",
"html_safe",
"when",
"'show'",
"then",
"t",
"(",
"'lines/buttons/preview'",
")",
".",
"html_safe",
"end",
"elsif",
"controller_path",
"==",
"'admin/authors'",
"case",
"action_name",
"when",
"'index'",
"then",
"t",
"(",
"'lines/buttons/all_authors'",
")",
".",
"html_safe",
"when",
"'new'",
"then",
"t",
"(",
"'lines/buttons/new_author'",
")",
".",
"html_safe",
"when",
"'edit'",
"then",
"t",
"(",
"'lines/buttons/edit_author'",
")",
".",
"html_safe",
"when",
"'show'",
"then",
"t",
"(",
"'lines/buttons/author'",
")",
".",
"html_safe",
"end",
"end",
"end"
] | Returns site name for actionbar, dependend on current site | [
"Returns",
"site",
"name",
"for",
"actionbar",
"dependend",
"on",
"current",
"site"
] | 9ae0525e882a9c323558353ce1941c50e8bcfc67 | https://github.com/opoloo/lines-engine/blob/9ae0525e882a9c323558353ce1941c50e8bcfc67/app/helpers/lines/application_helper.rb#L101-L117 | train |
opoloo/lines-engine | app/models/lines/user.rb | Lines.User.create_reset_digest | def create_reset_digest
self.reset_token = Lines::User.generate_token
update_attribute(:reset_digest, Lines::User.digest(reset_token))
update_attribute(:reset_sent_at, Time.zone.now)
end | ruby | def create_reset_digest
self.reset_token = Lines::User.generate_token
update_attribute(:reset_digest, Lines::User.digest(reset_token))
update_attribute(:reset_sent_at, Time.zone.now)
end | [
"def",
"create_reset_digest",
"self",
".",
"reset_token",
"=",
"Lines",
"::",
"User",
".",
"generate_token",
"update_attribute",
"(",
":reset_digest",
",",
"Lines",
"::",
"User",
".",
"digest",
"(",
"reset_token",
")",
")",
"update_attribute",
"(",
":reset_sent_at",
",",
"Time",
".",
"zone",
".",
"now",
")",
"end"
] | Sets +rest_digest+ and +reset_sent_at+ for password reset. | [
"Sets",
"+",
"rest_digest",
"+",
"and",
"+",
"reset_sent_at",
"+",
"for",
"password",
"reset",
"."
] | 9ae0525e882a9c323558353ce1941c50e8bcfc67 | https://github.com/opoloo/lines-engine/blob/9ae0525e882a9c323558353ce1941c50e8bcfc67/app/models/lines/user.rb#L29-L33 | train |
opoloo/lines-engine | app/controllers/lines/sessions_controller.rb | Lines.SessionsController.create | def create
user = Lines::User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to admin_root_url
else
flash.now[:error] = t('lines.login_error')
render "new"
end
end | ruby | def create
user = Lines::User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to admin_root_url
else
flash.now[:error] = t('lines.login_error')
render "new"
end
end | [
"def",
"create",
"user",
"=",
"Lines",
"::",
"User",
".",
"find_by",
"(",
"email",
":",
"params",
"[",
":email",
"]",
")",
"if",
"user",
"&&",
"user",
".",
"authenticate",
"(",
"params",
"[",
":password",
"]",
")",
"session",
"[",
":user_id",
"]",
"=",
"user",
".",
"id",
"redirect_to",
"admin_root_url",
"else",
"flash",
".",
"now",
"[",
":error",
"]",
"=",
"t",
"(",
"'lines.login_error'",
")",
"render",
"\"new\"",
"end",
"end"
] | Authenticate user and create a new session. | [
"Authenticate",
"user",
"and",
"create",
"a",
"new",
"session",
"."
] | 9ae0525e882a9c323558353ce1941c50e8bcfc67 | https://github.com/opoloo/lines-engine/blob/9ae0525e882a9c323558353ce1941c50e8bcfc67/app/controllers/lines/sessions_controller.rb#L16-L25 | train |
jedi4ever/veewee | lib/net/vnc/vnc.rb | Net.VNC.type | def type text, options={}
packet = 0.chr * 8
packet[0] = 4.chr
text.split(//).each do |char|
packet[7] = char[0]
packet[1] = 1.chr
socket.write packet
packet[1] = 0.chr
socket.write packet
end
wait options
end | ruby | def type text, options={}
packet = 0.chr * 8
packet[0] = 4.chr
text.split(//).each do |char|
packet[7] = char[0]
packet[1] = 1.chr
socket.write packet
packet[1] = 0.chr
socket.write packet
end
wait options
end | [
"def",
"type",
"text",
",",
"options",
"=",
"{",
"}",
"packet",
"=",
"0",
".",
"chr",
"*",
"8",
"packet",
"[",
"0",
"]",
"=",
"4",
".",
"chr",
"text",
".",
"split",
"(",
"/",
"/",
")",
".",
"each",
"do",
"|",
"char",
"|",
"packet",
"[",
"7",
"]",
"=",
"char",
"[",
"0",
"]",
"packet",
"[",
"1",
"]",
"=",
"1",
".",
"chr",
"socket",
".",
"write",
"packet",
"packet",
"[",
"1",
"]",
"=",
"0",
".",
"chr",
"socket",
".",
"write",
"packet",
"end",
"wait",
"options",
"end"
] | this types +text+ on the server | [
"this",
"types",
"+",
"text",
"+",
"on",
"the",
"server"
] | 0173803b6d9c22ca675247ae8fa853f5352e125b | https://github.com/jedi4ever/veewee/blob/0173803b6d9c22ca675247ae8fa853f5352e125b/lib/net/vnc/vnc.rb#L150-L161 | train |
jedi4ever/veewee | lib/net/vnc/vnc.rb | Net.VNC.type_string | def type_string text, options={}
shift_key_down = nil
text.each_char do |char|
key_to_press = KEY_PRESS_CHARS[char]
unless key_to_press.nil?
key_press key_to_press
else
key_needs_shift = SHIFTED_CHARS.include? char
if shift_key_down.nil? || shift_key_down != key_needs_shift
if key_needs_shift
key_down :shift
else
key_up :shift
end
end
type char
shift_key_down = key_needs_shift
end
end
wait options
end | ruby | def type_string text, options={}
shift_key_down = nil
text.each_char do |char|
key_to_press = KEY_PRESS_CHARS[char]
unless key_to_press.nil?
key_press key_to_press
else
key_needs_shift = SHIFTED_CHARS.include? char
if shift_key_down.nil? || shift_key_down != key_needs_shift
if key_needs_shift
key_down :shift
else
key_up :shift
end
end
type char
shift_key_down = key_needs_shift
end
end
wait options
end | [
"def",
"type_string",
"text",
",",
"options",
"=",
"{",
"}",
"shift_key_down",
"=",
"nil",
"text",
".",
"each_char",
"do",
"|",
"char",
"|",
"key_to_press",
"=",
"KEY_PRESS_CHARS",
"[",
"char",
"]",
"unless",
"key_to_press",
".",
"nil?",
"key_press",
"key_to_press",
"else",
"key_needs_shift",
"=",
"SHIFTED_CHARS",
".",
"include?",
"char",
"if",
"shift_key_down",
".",
"nil?",
"||",
"shift_key_down",
"!=",
"key_needs_shift",
"if",
"key_needs_shift",
"key_down",
":shift",
"else",
"key_up",
":shift",
"end",
"end",
"type",
"char",
"shift_key_down",
"=",
"key_needs_shift",
"end",
"end",
"wait",
"options",
"end"
] | This types +text+ on the server, but it holds the shift key down when necessary.
It will also execute key_press for tabs and returns. | [
"This",
"types",
"+",
"text",
"+",
"on",
"the",
"server",
"but",
"it",
"holds",
"the",
"shift",
"key",
"down",
"when",
"necessary",
".",
"It",
"will",
"also",
"execute",
"key_press",
"for",
"tabs",
"and",
"returns",
"."
] | 0173803b6d9c22ca675247ae8fa853f5352e125b | https://github.com/jedi4ever/veewee/blob/0173803b6d9c22ca675247ae8fa853f5352e125b/lib/net/vnc/vnc.rb#L171-L194 | train |
jedi4ever/veewee | lib/veewee/templates.rb | Veewee.Templates.valid_paths | def valid_paths(paths)
paths = GemContent.get_gem_paths("veewee-templates")
valid_paths = paths.collect { |path|
if File.exists?(path) && File.directory?(path)
env.logger.info "Path #{path} exists"
File.expand_path(path)
else
env.logger.info "Path #{path} does not exist, skipping"
nil
end
}
return valid_paths.compact
end | ruby | def valid_paths(paths)
paths = GemContent.get_gem_paths("veewee-templates")
valid_paths = paths.collect { |path|
if File.exists?(path) && File.directory?(path)
env.logger.info "Path #{path} exists"
File.expand_path(path)
else
env.logger.info "Path #{path} does not exist, skipping"
nil
end
}
return valid_paths.compact
end | [
"def",
"valid_paths",
"(",
"paths",
")",
"paths",
"=",
"GemContent",
".",
"get_gem_paths",
"(",
"\"veewee-templates\"",
")",
"valid_paths",
"=",
"paths",
".",
"collect",
"{",
"|",
"path",
"|",
"if",
"File",
".",
"exists?",
"(",
"path",
")",
"&&",
"File",
".",
"directory?",
"(",
"path",
")",
"env",
".",
"logger",
".",
"info",
"\"Path #{path} exists\"",
"File",
".",
"expand_path",
"(",
"path",
")",
"else",
"env",
".",
"logger",
".",
"info",
"\"Path #{path} does not exist, skipping\"",
"nil",
"end",
"}",
"return",
"valid_paths",
".",
"compact",
"end"
] | Traverses path to see which exist or not
and checks if available | [
"Traverses",
"path",
"to",
"see",
"which",
"exist",
"or",
"not",
"and",
"checks",
"if",
"available"
] | 0173803b6d9c22ca675247ae8fa853f5352e125b | https://github.com/jedi4ever/veewee/blob/0173803b6d9c22ca675247ae8fa853f5352e125b/lib/veewee/templates.rb#L57-L69 | train |
jedi4ever/veewee | lib/veewee/config.rb | Veewee.Config.load_veewee_config | def load_veewee_config()
veewee_configurator = self
begin
filename = @env.config_filepath
if File.exists?(filename)
env.logger.info("Loading config file: #{filename}")
veeweefile = File.read(filename)
veeweefile["Veewee::Config.run"] = "veewee_configurator.define"
# http://www.dan-manges.com/blog/ruby-dsls-instance-eval-with-delegation
instance_eval(veeweefile)
else
env.logger.info "No configfile found"
end
rescue LoadError => e
env.ui.error "An error occurred"
env.ui.error e.message
rescue NoMethodError => e
env.ui.error "Some method got an error in the configfile - Sorry"
env.ui.error $!
env.ui.error e.message
raise Veewee::Error "Some method got an error in the configfile - Sorry"
rescue Error => e
env.ui.error "Error processing configfile - Sorry"
env.ui.error e.message
raise Veewee::Error "Error processing configfile - Sorry"
end
return self
end | ruby | def load_veewee_config()
veewee_configurator = self
begin
filename = @env.config_filepath
if File.exists?(filename)
env.logger.info("Loading config file: #{filename}")
veeweefile = File.read(filename)
veeweefile["Veewee::Config.run"] = "veewee_configurator.define"
# http://www.dan-manges.com/blog/ruby-dsls-instance-eval-with-delegation
instance_eval(veeweefile)
else
env.logger.info "No configfile found"
end
rescue LoadError => e
env.ui.error "An error occurred"
env.ui.error e.message
rescue NoMethodError => e
env.ui.error "Some method got an error in the configfile - Sorry"
env.ui.error $!
env.ui.error e.message
raise Veewee::Error "Some method got an error in the configfile - Sorry"
rescue Error => e
env.ui.error "Error processing configfile - Sorry"
env.ui.error e.message
raise Veewee::Error "Error processing configfile - Sorry"
end
return self
end | [
"def",
"load_veewee_config",
"(",
")",
"veewee_configurator",
"=",
"self",
"begin",
"filename",
"=",
"@env",
".",
"config_filepath",
"if",
"File",
".",
"exists?",
"(",
"filename",
")",
"env",
".",
"logger",
".",
"info",
"(",
"\"Loading config file: #{filename}\"",
")",
"veeweefile",
"=",
"File",
".",
"read",
"(",
"filename",
")",
"veeweefile",
"[",
"\"Veewee::Config.run\"",
"]",
"=",
"\"veewee_configurator.define\"",
"# http://www.dan-manges.com/blog/ruby-dsls-instance-eval-with-delegation",
"instance_eval",
"(",
"veeweefile",
")",
"else",
"env",
".",
"logger",
".",
"info",
"\"No configfile found\"",
"end",
"rescue",
"LoadError",
"=>",
"e",
"env",
".",
"ui",
".",
"error",
"\"An error occurred\"",
"env",
".",
"ui",
".",
"error",
"e",
".",
"message",
"rescue",
"NoMethodError",
"=>",
"e",
"env",
".",
"ui",
".",
"error",
"\"Some method got an error in the configfile - Sorry\"",
"env",
".",
"ui",
".",
"error",
"$!",
"env",
".",
"ui",
".",
"error",
"e",
".",
"message",
"raise",
"Veewee",
"::",
"Error",
"\"Some method got an error in the configfile - Sorry\"",
"rescue",
"Error",
"=>",
"e",
"env",
".",
"ui",
".",
"error",
"\"Error processing configfile - Sorry\"",
"env",
".",
"ui",
".",
"error",
"e",
".",
"message",
"raise",
"Veewee",
"::",
"Error",
"\"Error processing configfile - Sorry\"",
"end",
"return",
"self",
"end"
] | We put a long name to not clash with any function in the Veewee file itself | [
"We",
"put",
"a",
"long",
"name",
"to",
"not",
"clash",
"with",
"any",
"function",
"in",
"the",
"Veewee",
"file",
"itself"
] | 0173803b6d9c22ca675247ae8fa853f5352e125b | https://github.com/jedi4ever/veewee/blob/0173803b6d9c22ca675247ae8fa853f5352e125b/lib/veewee/config.rb#L30-L57 | train |
jedi4ever/veewee | lib/veewee/definition.rb | Veewee.Definition.declare | def declare(options)
options.each do |key, value|
instance_variable_set("@#{key}".to_sym, options[key])
env.logger.info("definition") { " - #{key} : #{options[key]}" }
end
end | ruby | def declare(options)
options.each do |key, value|
instance_variable_set("@#{key}".to_sym, options[key])
env.logger.info("definition") { " - #{key} : #{options[key]}" }
end
end | [
"def",
"declare",
"(",
"options",
")",
"options",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"instance_variable_set",
"(",
"\"@#{key}\"",
".",
"to_sym",
",",
"options",
"[",
"key",
"]",
")",
"env",
".",
"logger",
".",
"info",
"(",
"\"definition\"",
")",
"{",
"\" - #{key} : #{options[key]}\"",
"}",
"end",
"end"
] | This function takes a hash of options and injects them into the definition | [
"This",
"function",
"takes",
"a",
"hash",
"of",
"options",
"and",
"injects",
"them",
"into",
"the",
"definition"
] | 0173803b6d9c22ca675247ae8fa853f5352e125b | https://github.com/jedi4ever/veewee/blob/0173803b6d9c22ca675247ae8fa853f5352e125b/lib/veewee/definition.rb#L120-L126 | train |
jedi4ever/veewee | lib/fission.old/vm.rb | Fission.VM.mac_address | def mac_address
raise ::Fission::Error,"VM #{@name} does not exist" unless self.exists?
line=File.new(vmx_path).grep(/^ethernet0.generatedAddress =/)
if line.nil?
#Fission.ui.output "Hmm, the vmx file #{vmx_path} does not contain a generated mac address "
return nil
end
address=line.first.split("=")[1].strip.split(/\"/)[1]
return address
end | ruby | def mac_address
raise ::Fission::Error,"VM #{@name} does not exist" unless self.exists?
line=File.new(vmx_path).grep(/^ethernet0.generatedAddress =/)
if line.nil?
#Fission.ui.output "Hmm, the vmx file #{vmx_path} does not contain a generated mac address "
return nil
end
address=line.first.split("=")[1].strip.split(/\"/)[1]
return address
end | [
"def",
"mac_address",
"raise",
"::",
"Fission",
"::",
"Error",
",",
"\"VM #{@name} does not exist\"",
"unless",
"self",
".",
"exists?",
"line",
"=",
"File",
".",
"new",
"(",
"vmx_path",
")",
".",
"grep",
"(",
"/",
"/",
")",
"if",
"line",
".",
"nil?",
"#Fission.ui.output \"Hmm, the vmx file #{vmx_path} does not contain a generated mac address \"",
"return",
"nil",
"end",
"address",
"=",
"line",
".",
"first",
".",
"split",
"(",
"\"=\"",
")",
"[",
"1",
"]",
".",
"strip",
".",
"split",
"(",
"/",
"\\\"",
"/",
")",
"[",
"1",
"]",
"return",
"address",
"end"
] | Retrieve the first mac address for a vm
This will only retrieve the first auto generate mac address | [
"Retrieve",
"the",
"first",
"mac",
"address",
"for",
"a",
"vm",
"This",
"will",
"only",
"retrieve",
"the",
"first",
"auto",
"generate",
"mac",
"address"
] | 0173803b6d9c22ca675247ae8fa853f5352e125b | https://github.com/jedi4ever/veewee/blob/0173803b6d9c22ca675247ae8fa853f5352e125b/lib/fission.old/vm.rb#L92-L102 | train |
jedi4ever/veewee | lib/fission.old/vm.rb | Fission.VM.ip_address | def ip_address
raise ::Fission::Error,"VM #{@name} does not exist" unless self.exists?
unless mac_address.nil?
lease=LeasesFile.new("/var/db/vmware/vmnet-dhcpd-vmnet8.leases").find_lease_by_mac(mac_address)
if lease.nil?
return nil
else
return lease.ip
end
else
# No mac address was found for this machine so we can't calculate the ip-address
return nil
end
end | ruby | def ip_address
raise ::Fission::Error,"VM #{@name} does not exist" unless self.exists?
unless mac_address.nil?
lease=LeasesFile.new("/var/db/vmware/vmnet-dhcpd-vmnet8.leases").find_lease_by_mac(mac_address)
if lease.nil?
return nil
else
return lease.ip
end
else
# No mac address was found for this machine so we can't calculate the ip-address
return nil
end
end | [
"def",
"ip_address",
"raise",
"::",
"Fission",
"::",
"Error",
",",
"\"VM #{@name} does not exist\"",
"unless",
"self",
".",
"exists?",
"unless",
"mac_address",
".",
"nil?",
"lease",
"=",
"LeasesFile",
".",
"new",
"(",
"\"/var/db/vmware/vmnet-dhcpd-vmnet8.leases\"",
")",
".",
"find_lease_by_mac",
"(",
"mac_address",
")",
"if",
"lease",
".",
"nil?",
"return",
"nil",
"else",
"return",
"lease",
".",
"ip",
"end",
"else",
"# No mac address was found for this machine so we can't calculate the ip-address",
"return",
"nil",
"end",
"end"
] | Retrieve the ip address for a vm.
This will only look for dynamically assigned ip address via vmware dhcp | [
"Retrieve",
"the",
"ip",
"address",
"for",
"a",
"vm",
".",
"This",
"will",
"only",
"look",
"for",
"dynamically",
"assigned",
"ip",
"address",
"via",
"vmware",
"dhcp"
] | 0173803b6d9c22ca675247ae8fa853f5352e125b | https://github.com/jedi4ever/veewee/blob/0173803b6d9c22ca675247ae8fa853f5352e125b/lib/fission.old/vm.rb#L106-L120 | train |
jedi4ever/veewee | lib/veewee/definitions.rb | Veewee.Definitions.each | def each(&block)
definitions = Hash.new
env.logger.debug("[Definition] Searching #{env.definition_dir} for definitions:")
subdirs = Dir.glob("#{env.definition_dir}/*")
subdirs.each do |sub|
name = File.basename(sub)
env.logger.debug("[Definition] possible definition '#{name}' found")
begin
definitions[name] = Veewee::Definition.load(name, env)
rescue Veewee::DefinitionError => ex
env.logger.debug("[Definition] failed to load definition from directory '#{name}' #{ex}")
end
end
if definitions.length == 0
env.logger.debug("[Definition] no definitions found")
end
definitions.each(&block)
end | ruby | def each(&block)
definitions = Hash.new
env.logger.debug("[Definition] Searching #{env.definition_dir} for definitions:")
subdirs = Dir.glob("#{env.definition_dir}/*")
subdirs.each do |sub|
name = File.basename(sub)
env.logger.debug("[Definition] possible definition '#{name}' found")
begin
definitions[name] = Veewee::Definition.load(name, env)
rescue Veewee::DefinitionError => ex
env.logger.debug("[Definition] failed to load definition from directory '#{name}' #{ex}")
end
end
if definitions.length == 0
env.logger.debug("[Definition] no definitions found")
end
definitions.each(&block)
end | [
"def",
"each",
"(",
"&",
"block",
")",
"definitions",
"=",
"Hash",
".",
"new",
"env",
".",
"logger",
".",
"debug",
"(",
"\"[Definition] Searching #{env.definition_dir} for definitions:\"",
")",
"subdirs",
"=",
"Dir",
".",
"glob",
"(",
"\"#{env.definition_dir}/*\"",
")",
"subdirs",
".",
"each",
"do",
"|",
"sub",
"|",
"name",
"=",
"File",
".",
"basename",
"(",
"sub",
")",
"env",
".",
"logger",
".",
"debug",
"(",
"\"[Definition] possible definition '#{name}' found\"",
")",
"begin",
"definitions",
"[",
"name",
"]",
"=",
"Veewee",
"::",
"Definition",
".",
"load",
"(",
"name",
",",
"env",
")",
"rescue",
"Veewee",
"::",
"DefinitionError",
"=>",
"ex",
"env",
".",
"logger",
".",
"debug",
"(",
"\"[Definition] failed to load definition from directory '#{name}' #{ex}\"",
")",
"end",
"end",
"if",
"definitions",
".",
"length",
"==",
"0",
"env",
".",
"logger",
".",
"debug",
"(",
"\"[Definition] no definitions found\"",
")",
"end",
"definitions",
".",
"each",
"(",
"block",
")",
"end"
] | Fetch all definitions | [
"Fetch",
"all",
"definitions"
] | 0173803b6d9c22ca675247ae8fa853f5352e125b | https://github.com/jedi4ever/veewee/blob/0173803b6d9c22ca675247ae8fa853f5352e125b/lib/veewee/definitions.rb#L31-L52 | train |
cloudfoundry/cf-uaac | spec/spec_helper.rb | CF::UAA.SpecHelper.frequest | def frequest(on_fiber, &blk)
return capture_exception(&blk) unless on_fiber
result, cthred = nil, Thread.current
EM.schedule { Fiber.new { result = capture_exception(&blk); cthred.run }.resume }
Thread.stop
result
end | ruby | def frequest(on_fiber, &blk)
return capture_exception(&blk) unless on_fiber
result, cthred = nil, Thread.current
EM.schedule { Fiber.new { result = capture_exception(&blk); cthred.run }.resume }
Thread.stop
result
end | [
"def",
"frequest",
"(",
"on_fiber",
",",
"&",
"blk",
")",
"return",
"capture_exception",
"(",
"blk",
")",
"unless",
"on_fiber",
"result",
",",
"cthred",
"=",
"nil",
",",
"Thread",
".",
"current",
"EM",
".",
"schedule",
"{",
"Fiber",
".",
"new",
"{",
"result",
"=",
"capture_exception",
"(",
"blk",
")",
";",
"cthred",
".",
"run",
"}",
".",
"resume",
"}",
"Thread",
".",
"stop",
"result",
"end"
] | Runs given block on a thread or fiber and returns result.
If eventmachine is running on another thread, the fiber
must be on the same thread, hence EM.schedule and the
restriction that the given block cannot include rspec matchers. | [
"Runs",
"given",
"block",
"on",
"a",
"thread",
"or",
"fiber",
"and",
"returns",
"result",
".",
"If",
"eventmachine",
"is",
"running",
"on",
"another",
"thread",
"the",
"fiber",
"must",
"be",
"on",
"the",
"same",
"thread",
"hence",
"EM",
".",
"schedule",
"and",
"the",
"restriction",
"that",
"the",
"given",
"block",
"cannot",
"include",
"rspec",
"matchers",
"."
] | eb9169d498e4a7ea644823227e4872600a2e5ef0 | https://github.com/cloudfoundry/cf-uaac/blob/eb9169d498e4a7ea644823227e4872600a2e5ef0/spec/spec_helper.rb#L43-L49 | train |
cloudfoundry/cf-uaac | lib/uaa/stub/uaa.rb | CF::UAA.StubUAAConn.bad_params? | def bad_params?(params, required, optional = nil)
required.each {|r|
next if params[r]
reply.json(400, error: 'invalid_request', error_description: "no #{r} in request")
return true
}
return false unless optional
params.each {|k, v|
next if required.include?(k) || optional.include?(k)
reply.json(400, error: 'invalid_request', error_description: "#{k} not allowed")
return true
}
false
end | ruby | def bad_params?(params, required, optional = nil)
required.each {|r|
next if params[r]
reply.json(400, error: 'invalid_request', error_description: "no #{r} in request")
return true
}
return false unless optional
params.each {|k, v|
next if required.include?(k) || optional.include?(k)
reply.json(400, error: 'invalid_request', error_description: "#{k} not allowed")
return true
}
false
end | [
"def",
"bad_params?",
"(",
"params",
",",
"required",
",",
"optional",
"=",
"nil",
")",
"required",
".",
"each",
"{",
"|",
"r",
"|",
"next",
"if",
"params",
"[",
"r",
"]",
"reply",
".",
"json",
"(",
"400",
",",
"error",
":",
"'invalid_request'",
",",
"error_description",
":",
"\"no #{r} in request\"",
")",
"return",
"true",
"}",
"return",
"false",
"unless",
"optional",
"params",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"next",
"if",
"required",
".",
"include?",
"(",
"k",
")",
"||",
"optional",
".",
"include?",
"(",
"k",
")",
"reply",
".",
"json",
"(",
"400",
",",
"error",
":",
"'invalid_request'",
",",
"error_description",
":",
"\"#{k} not allowed\"",
")",
"return",
"true",
"}",
"false",
"end"
] | if required and optional arrays are given, extra params are an error | [
"if",
"required",
"and",
"optional",
"arrays",
"are",
"given",
"extra",
"params",
"are",
"an",
"error"
] | eb9169d498e4a7ea644823227e4872600a2e5ef0 | https://github.com/cloudfoundry/cf-uaac/blob/eb9169d498e4a7ea644823227e4872600a2e5ef0/lib/uaa/stub/uaa.rb#L258-L271 | train |
cloudfoundry/cf-uaac | lib/uaa/stub/server.rb | Stub.Request.completed? | def completed?(str)
str, @prelude = @prelude + str, "" unless @prelude.empty?
add_lines(str)
return unless @state == :body && @body.bytesize >= @content_length
@prelude = bslice(@body, @content_length..-1)
@body = bslice(@body, 0..@content_length)
@state = :init
end | ruby | def completed?(str)
str, @prelude = @prelude + str, "" unless @prelude.empty?
add_lines(str)
return unless @state == :body && @body.bytesize >= @content_length
@prelude = bslice(@body, @content_length..-1)
@body = bslice(@body, 0..@content_length)
@state = :init
end | [
"def",
"completed?",
"(",
"str",
")",
"str",
",",
"@prelude",
"=",
"@prelude",
"+",
"str",
",",
"\"\"",
"unless",
"@prelude",
".",
"empty?",
"add_lines",
"(",
"str",
")",
"return",
"unless",
"@state",
"==",
":body",
"&&",
"@body",
".",
"bytesize",
">=",
"@content_length",
"@prelude",
"=",
"bslice",
"(",
"@body",
",",
"@content_length",
"..",
"-",
"1",
")",
"@body",
"=",
"bslice",
"(",
"@body",
",",
"0",
"..",
"@content_length",
")",
"@state",
"=",
":init",
"end"
] | adds data to the request, returns true if request is complete | [
"adds",
"data",
"to",
"the",
"request",
"returns",
"true",
"if",
"request",
"is",
"complete"
] | eb9169d498e4a7ea644823227e4872600a2e5ef0 | https://github.com/cloudfoundry/cf-uaac/blob/eb9169d498e4a7ea644823227e4872600a2e5ef0/lib/uaa/stub/server.rb#L68-L75 | train |
jruby/activerecord-jdbc-adapter | lib/arjdbc/derby/adapter.rb | ArJdbc.Derby.type_to_sql | def type_to_sql(type, limit = nil, precision = nil, scale = nil)
return super unless NO_LIMIT_TYPES.include?(t = type.to_s.downcase.to_sym)
native_type = NATIVE_DATABASE_TYPES[t]
native_type.is_a?(Hash) ? native_type[:name] : native_type
end | ruby | def type_to_sql(type, limit = nil, precision = nil, scale = nil)
return super unless NO_LIMIT_TYPES.include?(t = type.to_s.downcase.to_sym)
native_type = NATIVE_DATABASE_TYPES[t]
native_type.is_a?(Hash) ? native_type[:name] : native_type
end | [
"def",
"type_to_sql",
"(",
"type",
",",
"limit",
"=",
"nil",
",",
"precision",
"=",
"nil",
",",
"scale",
"=",
"nil",
")",
"return",
"super",
"unless",
"NO_LIMIT_TYPES",
".",
"include?",
"(",
"t",
"=",
"type",
".",
"to_s",
".",
"downcase",
".",
"to_sym",
")",
"native_type",
"=",
"NATIVE_DATABASE_TYPES",
"[",
"t",
"]",
"native_type",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"native_type",
"[",
":name",
"]",
":",
"native_type",
"end"
] | Convert the specified column type to a SQL string.
@override | [
"Convert",
"the",
"specified",
"column",
"type",
"to",
"a",
"SQL",
"string",
"."
] | 897fd95514f565b7325eed0d9e3369378ad03fe5 | https://github.com/jruby/activerecord-jdbc-adapter/blob/897fd95514f565b7325eed0d9e3369378ad03fe5/lib/arjdbc/derby/adapter.rb#L231-L236 | train |
jruby/activerecord-jdbc-adapter | lib/arjdbc/oracle/adapter.rb | ArJdbc.Oracle.default_owner | def default_owner
unless defined? @default_owner
username = config[:username] ? config[:username].to_s : jdbc_connection.meta_data.user_name
@default_owner = username.nil? ? nil : username.upcase
end
@default_owner
end | ruby | def default_owner
unless defined? @default_owner
username = config[:username] ? config[:username].to_s : jdbc_connection.meta_data.user_name
@default_owner = username.nil? ? nil : username.upcase
end
@default_owner
end | [
"def",
"default_owner",
"unless",
"defined?",
"@default_owner",
"username",
"=",
"config",
"[",
":username",
"]",
"?",
"config",
"[",
":username",
"]",
".",
"to_s",
":",
"jdbc_connection",
".",
"meta_data",
".",
"user_name",
"@default_owner",
"=",
"username",
".",
"nil?",
"?",
"nil",
":",
"username",
".",
"upcase",
"end",
"@default_owner",
"end"
] | default schema owner | [
"default",
"schema",
"owner"
] | 897fd95514f565b7325eed0d9e3369378ad03fe5 | https://github.com/jruby/activerecord-jdbc-adapter/blob/897fd95514f565b7325eed0d9e3369378ad03fe5/lib/arjdbc/oracle/adapter.rb#L810-L816 | train |
jruby/activerecord-jdbc-adapter | lib/arjdbc/db2/as400.rb | ArJdbc.AS400.execute_and_auto_confirm | def execute_and_auto_confirm(sql, name = nil)
begin
@connection.execute_update "call qsys.qcmdexc('QSYS/CHGJOB INQMSGRPY(*SYSRPYL)',0000000031.00000)"
@connection.execute_update "call qsys.qcmdexc('ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY(''I'')',0000000045.00000)"
rescue Exception => e
raise "Could not call CHGJOB INQMSGRPY(*SYSRPYL) and ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I').\n" +
"Do you have authority to do this?\n\n#{e.inspect}"
end
begin
result = execute(sql, name)
rescue Exception
raise
else
# Return if all work fine
result
ensure
# Ensure default configuration restoration
begin
@connection.execute_update "call qsys.qcmdexc('QSYS/CHGJOB INQMSGRPY(*DFT)',0000000027.00000)"
@connection.execute_update "call qsys.qcmdexc('RMVRPYLE SEQNBR(9876)',0000000021.00000)"
rescue Exception => e
raise "Could not call CHGJOB INQMSGRPY(*DFT) and RMVRPYLE SEQNBR(9876).\n" +
"Do you have authority to do this?\n\n#{e.inspect}"
end
end
end | ruby | def execute_and_auto_confirm(sql, name = nil)
begin
@connection.execute_update "call qsys.qcmdexc('QSYS/CHGJOB INQMSGRPY(*SYSRPYL)',0000000031.00000)"
@connection.execute_update "call qsys.qcmdexc('ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY(''I'')',0000000045.00000)"
rescue Exception => e
raise "Could not call CHGJOB INQMSGRPY(*SYSRPYL) and ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I').\n" +
"Do you have authority to do this?\n\n#{e.inspect}"
end
begin
result = execute(sql, name)
rescue Exception
raise
else
# Return if all work fine
result
ensure
# Ensure default configuration restoration
begin
@connection.execute_update "call qsys.qcmdexc('QSYS/CHGJOB INQMSGRPY(*DFT)',0000000027.00000)"
@connection.execute_update "call qsys.qcmdexc('RMVRPYLE SEQNBR(9876)',0000000021.00000)"
rescue Exception => e
raise "Could not call CHGJOB INQMSGRPY(*DFT) and RMVRPYLE SEQNBR(9876).\n" +
"Do you have authority to do this?\n\n#{e.inspect}"
end
end
end | [
"def",
"execute_and_auto_confirm",
"(",
"sql",
",",
"name",
"=",
"nil",
")",
"begin",
"@connection",
".",
"execute_update",
"\"call qsys.qcmdexc('QSYS/CHGJOB INQMSGRPY(*SYSRPYL)',0000000031.00000)\"",
"@connection",
".",
"execute_update",
"\"call qsys.qcmdexc('ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY(''I'')',0000000045.00000)\"",
"rescue",
"Exception",
"=>",
"e",
"raise",
"\"Could not call CHGJOB INQMSGRPY(*SYSRPYL) and ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I').\\n\"",
"+",
"\"Do you have authority to do this?\\n\\n#{e.inspect}\"",
"end",
"begin",
"result",
"=",
"execute",
"(",
"sql",
",",
"name",
")",
"rescue",
"Exception",
"raise",
"else",
"# Return if all work fine",
"result",
"ensure",
"# Ensure default configuration restoration",
"begin",
"@connection",
".",
"execute_update",
"\"call qsys.qcmdexc('QSYS/CHGJOB INQMSGRPY(*DFT)',0000000027.00000)\"",
"@connection",
".",
"execute_update",
"\"call qsys.qcmdexc('RMVRPYLE SEQNBR(9876)',0000000021.00000)\"",
"rescue",
"Exception",
"=>",
"e",
"raise",
"\"Could not call CHGJOB INQMSGRPY(*DFT) and RMVRPYLE SEQNBR(9876).\\n\"",
"+",
"\"Do you have authority to do this?\\n\\n#{e.inspect}\"",
"end",
"end",
"end"
] | holy moly batman! all this to tell AS400 "yes i am sure" | [
"holy",
"moly",
"batman!",
"all",
"this",
"to",
"tell",
"AS400",
"yes",
"i",
"am",
"sure"
] | 897fd95514f565b7325eed0d9e3369378ad03fe5 | https://github.com/jruby/activerecord-jdbc-adapter/blob/897fd95514f565b7325eed0d9e3369378ad03fe5/lib/arjdbc/db2/as400.rb#L66-L95 | train |
jruby/activerecord-jdbc-adapter | lib/arjdbc/db2/as400.rb | ArJdbc.AS400.table_exists? | def table_exists?(name)
return false unless name
schema ? @connection.table_exists?(name, schema) : @connection.table_exists?(name)
end | ruby | def table_exists?(name)
return false unless name
schema ? @connection.table_exists?(name, schema) : @connection.table_exists?(name)
end | [
"def",
"table_exists?",
"(",
"name",
")",
"return",
"false",
"unless",
"name",
"schema",
"?",
"@connection",
".",
"table_exists?",
"(",
"name",
",",
"schema",
")",
":",
"@connection",
".",
"table_exists?",
"(",
"name",
")",
"end"
] | disable all schemas browsing when default schema is specified | [
"disable",
"all",
"schemas",
"browsing",
"when",
"default",
"schema",
"is",
"specified"
] | 897fd95514f565b7325eed0d9e3369378ad03fe5 | https://github.com/jruby/activerecord-jdbc-adapter/blob/897fd95514f565b7325eed0d9e3369378ad03fe5/lib/arjdbc/db2/as400.rb#L99-L102 | train |
jruby/activerecord-jdbc-adapter | lib/arjdbc/mssql/adapter.rb | ArJdbc.MSSQL.exec_proc | def exec_proc(proc_name, *variables)
vars =
if variables.any? && variables.first.is_a?(Hash)
variables.first.map { |k, v| "@#{k} = #{quote(v)}" }
else
variables.map { |v| quote(v) }
end.join(', ')
sql = "EXEC #{proc_name} #{vars}".strip
log(sql, 'Execute Procedure') do
result = @connection.execute_query_raw(sql)
result.map! do |row|
row = row.is_a?(Hash) ? row.with_indifferent_access : row
yield(row) if block_given?
row
end
result
end
end | ruby | def exec_proc(proc_name, *variables)
vars =
if variables.any? && variables.first.is_a?(Hash)
variables.first.map { |k, v| "@#{k} = #{quote(v)}" }
else
variables.map { |v| quote(v) }
end.join(', ')
sql = "EXEC #{proc_name} #{vars}".strip
log(sql, 'Execute Procedure') do
result = @connection.execute_query_raw(sql)
result.map! do |row|
row = row.is_a?(Hash) ? row.with_indifferent_access : row
yield(row) if block_given?
row
end
result
end
end | [
"def",
"exec_proc",
"(",
"proc_name",
",",
"*",
"variables",
")",
"vars",
"=",
"if",
"variables",
".",
"any?",
"&&",
"variables",
".",
"first",
".",
"is_a?",
"(",
"Hash",
")",
"variables",
".",
"first",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"\"@#{k} = #{quote(v)}\"",
"}",
"else",
"variables",
".",
"map",
"{",
"|",
"v",
"|",
"quote",
"(",
"v",
")",
"}",
"end",
".",
"join",
"(",
"', '",
")",
"sql",
"=",
"\"EXEC #{proc_name} #{vars}\"",
".",
"strip",
"log",
"(",
"sql",
",",
"'Execute Procedure'",
")",
"do",
"result",
"=",
"@connection",
".",
"execute_query_raw",
"(",
"sql",
")",
"result",
".",
"map!",
"do",
"|",
"row",
"|",
"row",
"=",
"row",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"row",
".",
"with_indifferent_access",
":",
"row",
"yield",
"(",
"row",
")",
"if",
"block_given?",
"row",
"end",
"result",
"end",
"end"
] | Support for executing a stored procedure. | [
"Support",
"for",
"executing",
"a",
"stored",
"procedure",
"."
] | 897fd95514f565b7325eed0d9e3369378ad03fe5 | https://github.com/jruby/activerecord-jdbc-adapter/blob/897fd95514f565b7325eed0d9e3369378ad03fe5/lib/arjdbc/mssql/adapter.rb#L652-L669 | train |
jruby/activerecord-jdbc-adapter | lib/arjdbc/mssql/adapter.rb | ArJdbc.MSSQL.exec_query | def exec_query(sql, name = 'SQL', binds = [])
# NOTE: we allow to execute SQL as requested returning a results.
# e.g. this allows to use SQLServer's EXEC with a result set ...
sql = to_sql(sql, binds) if sql.respond_to?(:to_sql)
sql = repair_special_columns(sql)
if prepared_statements?
log(sql, name, binds) { @connection.execute_query(sql, binds) }
else
log(sql, name) { @connection.execute_query(sql) }
end
end | ruby | def exec_query(sql, name = 'SQL', binds = [])
# NOTE: we allow to execute SQL as requested returning a results.
# e.g. this allows to use SQLServer's EXEC with a result set ...
sql = to_sql(sql, binds) if sql.respond_to?(:to_sql)
sql = repair_special_columns(sql)
if prepared_statements?
log(sql, name, binds) { @connection.execute_query(sql, binds) }
else
log(sql, name) { @connection.execute_query(sql) }
end
end | [
"def",
"exec_query",
"(",
"sql",
",",
"name",
"=",
"'SQL'",
",",
"binds",
"=",
"[",
"]",
")",
"# NOTE: we allow to execute SQL as requested returning a results.",
"# e.g. this allows to use SQLServer's EXEC with a result set ...",
"sql",
"=",
"to_sql",
"(",
"sql",
",",
"binds",
")",
"if",
"sql",
".",
"respond_to?",
"(",
":to_sql",
")",
"sql",
"=",
"repair_special_columns",
"(",
"sql",
")",
"if",
"prepared_statements?",
"log",
"(",
"sql",
",",
"name",
",",
"binds",
")",
"{",
"@connection",
".",
"execute_query",
"(",
"sql",
",",
"binds",
")",
"}",
"else",
"log",
"(",
"sql",
",",
"name",
")",
"{",
"@connection",
".",
"execute_query",
"(",
"sql",
")",
"}",
"end",
"end"
] | AR-SQLServer-Adapter naming
@override | [
"AR",
"-",
"SQLServer",
"-",
"Adapter",
"naming"
] | 897fd95514f565b7325eed0d9e3369378ad03fe5 | https://github.com/jruby/activerecord-jdbc-adapter/blob/897fd95514f565b7325eed0d9e3369378ad03fe5/lib/arjdbc/mssql/adapter.rb#L673-L684 | train |
jruby/activerecord-jdbc-adapter | lib/arjdbc/postgresql/adapter.rb | ArJdbc.PostgreSQL.configure_connection | def configure_connection
#if encoding = config[:encoding]
# The client_encoding setting is set by the driver and should not be altered.
# If the driver detects a change it will abort the connection.
# see http://jdbc.postgresql.org/documentation/91/connect.html
# self.set_client_encoding(encoding)
#end
self.client_min_messages = config[:min_messages] || 'warning'
self.schema_search_path = config[:schema_search_path] || config[:schema_order]
# Use standard-conforming strings if available so we don't have to do the E'...' dance.
set_standard_conforming_strings
# If using Active Record's time zone support configure the connection to return
# TIMESTAMP WITH ZONE types in UTC.
# (SET TIME ZONE does not use an equals sign like other SET variables)
if ActiveRecord::Base.default_timezone == :utc
execute("SET time zone 'UTC'", 'SCHEMA')
elsif tz = local_tz
execute("SET time zone '#{tz}'", 'SCHEMA')
end unless redshift?
# SET statements from :variables config hash
# http://www.postgresql.org/docs/8.3/static/sql-set.html
(config[:variables] || {}).map do |k, v|
if v == ':default' || v == :default
# Sets the value to the global or compile default
execute("SET SESSION #{k} TO DEFAULT", 'SCHEMA')
elsif ! v.nil?
execute("SET SESSION #{k} TO #{quote(v)}", 'SCHEMA')
end
end
end | ruby | def configure_connection
#if encoding = config[:encoding]
# The client_encoding setting is set by the driver and should not be altered.
# If the driver detects a change it will abort the connection.
# see http://jdbc.postgresql.org/documentation/91/connect.html
# self.set_client_encoding(encoding)
#end
self.client_min_messages = config[:min_messages] || 'warning'
self.schema_search_path = config[:schema_search_path] || config[:schema_order]
# Use standard-conforming strings if available so we don't have to do the E'...' dance.
set_standard_conforming_strings
# If using Active Record's time zone support configure the connection to return
# TIMESTAMP WITH ZONE types in UTC.
# (SET TIME ZONE does not use an equals sign like other SET variables)
if ActiveRecord::Base.default_timezone == :utc
execute("SET time zone 'UTC'", 'SCHEMA')
elsif tz = local_tz
execute("SET time zone '#{tz}'", 'SCHEMA')
end unless redshift?
# SET statements from :variables config hash
# http://www.postgresql.org/docs/8.3/static/sql-set.html
(config[:variables] || {}).map do |k, v|
if v == ':default' || v == :default
# Sets the value to the global or compile default
execute("SET SESSION #{k} TO DEFAULT", 'SCHEMA')
elsif ! v.nil?
execute("SET SESSION #{k} TO #{quote(v)}", 'SCHEMA')
end
end
end | [
"def",
"configure_connection",
"#if encoding = config[:encoding]",
"# The client_encoding setting is set by the driver and should not be altered.",
"# If the driver detects a change it will abort the connection.",
"# see http://jdbc.postgresql.org/documentation/91/connect.html",
"# self.set_client_encoding(encoding)",
"#end",
"self",
".",
"client_min_messages",
"=",
"config",
"[",
":min_messages",
"]",
"||",
"'warning'",
"self",
".",
"schema_search_path",
"=",
"config",
"[",
":schema_search_path",
"]",
"||",
"config",
"[",
":schema_order",
"]",
"# Use standard-conforming strings if available so we don't have to do the E'...' dance.",
"set_standard_conforming_strings",
"# If using Active Record's time zone support configure the connection to return",
"# TIMESTAMP WITH ZONE types in UTC.",
"# (SET TIME ZONE does not use an equals sign like other SET variables)",
"if",
"ActiveRecord",
"::",
"Base",
".",
"default_timezone",
"==",
":utc",
"execute",
"(",
"\"SET time zone 'UTC'\"",
",",
"'SCHEMA'",
")",
"elsif",
"tz",
"=",
"local_tz",
"execute",
"(",
"\"SET time zone '#{tz}'\"",
",",
"'SCHEMA'",
")",
"end",
"unless",
"redshift?",
"# SET statements from :variables config hash",
"# http://www.postgresql.org/docs/8.3/static/sql-set.html",
"(",
"config",
"[",
":variables",
"]",
"||",
"{",
"}",
")",
".",
"map",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"v",
"==",
"':default'",
"||",
"v",
"==",
":default",
"# Sets the value to the global or compile default",
"execute",
"(",
"\"SET SESSION #{k} TO DEFAULT\"",
",",
"'SCHEMA'",
")",
"elsif",
"!",
"v",
".",
"nil?",
"execute",
"(",
"\"SET SESSION #{k} TO #{quote(v)}\"",
",",
"'SCHEMA'",
")",
"end",
"end",
"end"
] | Configures the encoding, verbosity, schema search path, and time zone of the connection.
This is called on `connection.connect` and should not be called manually. | [
"Configures",
"the",
"encoding",
"verbosity",
"schema",
"search",
"path",
"and",
"time",
"zone",
"of",
"the",
"connection",
".",
"This",
"is",
"called",
"on",
"connection",
".",
"connect",
"and",
"should",
"not",
"be",
"called",
"manually",
"."
] | 897fd95514f565b7325eed0d9e3369378ad03fe5 | https://github.com/jruby/activerecord-jdbc-adapter/blob/897fd95514f565b7325eed0d9e3369378ad03fe5/lib/arjdbc/postgresql/adapter.rb#L108-L140 | train |
collectiveidea/delayed_job_active_record | lib/generators/delayed_job/next_migration_version.rb | DelayedJob.NextMigrationVersion.next_migration_number | def next_migration_number(dirname)
next_migration_number = current_migration_number(dirname) + 1
if ActiveRecord::Base.timestamped_migrations
[Time.now.utc.strftime("%Y%m%d%H%M%S"), format("%.14d", next_migration_number)].max
else
format("%.3d", next_migration_number)
end
end | ruby | def next_migration_number(dirname)
next_migration_number = current_migration_number(dirname) + 1
if ActiveRecord::Base.timestamped_migrations
[Time.now.utc.strftime("%Y%m%d%H%M%S"), format("%.14d", next_migration_number)].max
else
format("%.3d", next_migration_number)
end
end | [
"def",
"next_migration_number",
"(",
"dirname",
")",
"next_migration_number",
"=",
"current_migration_number",
"(",
"dirname",
")",
"+",
"1",
"if",
"ActiveRecord",
"::",
"Base",
".",
"timestamped_migrations",
"[",
"Time",
".",
"now",
".",
"utc",
".",
"strftime",
"(",
"\"%Y%m%d%H%M%S\"",
")",
",",
"format",
"(",
"\"%.14d\"",
",",
"next_migration_number",
")",
"]",
".",
"max",
"else",
"format",
"(",
"\"%.3d\"",
",",
"next_migration_number",
")",
"end",
"end"
] | while methods have moved around this has been the implementation
since ActiveRecord 3.0 | [
"while",
"methods",
"have",
"moved",
"around",
"this",
"has",
"been",
"the",
"implementation",
"since",
"ActiveRecord",
"3",
".",
"0"
] | 86de647e7e38ad115516f758f5a0d6fd0973df6d | https://github.com/collectiveidea/delayed_job_active_record/blob/86de647e7e38ad115516f758f5a0d6fd0973df6d/lib/generators/delayed_job/next_migration_version.rb#L5-L12 | train |
WeAreFarmGeek/diplomat | lib/diplomat/maintenance.rb | Diplomat.Maintenance.enabled | def enabled(n, options = {})
health = Diplomat::Health.new(@conn)
result = health.node(n, options)
.select { |check| check['CheckID'] == '_node_maintenance' }
if result.empty?
{ enabled: false, reason: nil }
else
{ enabled: true, reason: result.first['Notes'] }
end
end | ruby | def enabled(n, options = {})
health = Diplomat::Health.new(@conn)
result = health.node(n, options)
.select { |check| check['CheckID'] == '_node_maintenance' }
if result.empty?
{ enabled: false, reason: nil }
else
{ enabled: true, reason: result.first['Notes'] }
end
end | [
"def",
"enabled",
"(",
"n",
",",
"options",
"=",
"{",
"}",
")",
"health",
"=",
"Diplomat",
"::",
"Health",
".",
"new",
"(",
"@conn",
")",
"result",
"=",
"health",
".",
"node",
"(",
"n",
",",
"options",
")",
".",
"select",
"{",
"|",
"check",
"|",
"check",
"[",
"'CheckID'",
"]",
"==",
"'_node_maintenance'",
"}",
"if",
"result",
".",
"empty?",
"{",
"enabled",
":",
"false",
",",
"reason",
":",
"nil",
"}",
"else",
"{",
"enabled",
":",
"true",
",",
"reason",
":",
"result",
".",
"first",
"[",
"'Notes'",
"]",
"}",
"end",
"end"
] | Get the maintenance state of a host
@param n [String] the node
@param options [Hash] :dc string for dc specific query
@return [Hash] { :enabled => true, :reason => 'foo' } | [
"Get",
"the",
"maintenance",
"state",
"of",
"a",
"host"
] | cb6d06dc4ec965c30bbaf22017fd0db64b9b7677 | https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/maintenance.rb#L10-L20 | train |
WeAreFarmGeek/diplomat | lib/diplomat/maintenance.rb | Diplomat.Maintenance.enable | def enable(enable = true, reason = nil, options = {})
custom_params = []
custom_params << use_named_parameter('enable', enable.to_s)
custom_params << use_named_parameter('reason', reason) if reason
custom_params << use_named_parameter('dc', options[:dc]) if options[:dc]
raw = send_put_request(@conn, ['/v1/agent/maintenance'], options, nil, custom_params)
return_status = raw.status == 200
raise Diplomat::UnknownStatus, "status #{raw.status}: #{raw.body}" unless return_status
return_status
end | ruby | def enable(enable = true, reason = nil, options = {})
custom_params = []
custom_params << use_named_parameter('enable', enable.to_s)
custom_params << use_named_parameter('reason', reason) if reason
custom_params << use_named_parameter('dc', options[:dc]) if options[:dc]
raw = send_put_request(@conn, ['/v1/agent/maintenance'], options, nil, custom_params)
return_status = raw.status == 200
raise Diplomat::UnknownStatus, "status #{raw.status}: #{raw.body}" unless return_status
return_status
end | [
"def",
"enable",
"(",
"enable",
"=",
"true",
",",
"reason",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"custom_params",
"=",
"[",
"]",
"custom_params",
"<<",
"use_named_parameter",
"(",
"'enable'",
",",
"enable",
".",
"to_s",
")",
"custom_params",
"<<",
"use_named_parameter",
"(",
"'reason'",
",",
"reason",
")",
"if",
"reason",
"custom_params",
"<<",
"use_named_parameter",
"(",
"'dc'",
",",
"options",
"[",
":dc",
"]",
")",
"if",
"options",
"[",
":dc",
"]",
"raw",
"=",
"send_put_request",
"(",
"@conn",
",",
"[",
"'/v1/agent/maintenance'",
"]",
",",
"options",
",",
"nil",
",",
"custom_params",
")",
"return_status",
"=",
"raw",
".",
"status",
"==",
"200",
"raise",
"Diplomat",
"::",
"UnknownStatus",
",",
"\"status #{raw.status}: #{raw.body}\"",
"unless",
"return_status",
"return_status",
"end"
] | Enable or disable maintenance mode. This endpoint only works
on the local agent.
@param enable enable or disable maintenance mode
@param reason [String] the reason for enabling maintenance mode
@param options [Hash] :dc string for dc specific query
@return true if call is successful | [
"Enable",
"or",
"disable",
"maintenance",
"mode",
".",
"This",
"endpoint",
"only",
"works",
"on",
"the",
"local",
"agent",
"."
] | cb6d06dc4ec965c30bbaf22017fd0db64b9b7677 | https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/maintenance.rb#L28-L39 | train |
WeAreFarmGeek/diplomat | lib/diplomat/session.rb | Diplomat.Session.create | def create(value = nil, options = {})
# TODO: only certain keys are recognised in a session create request,
# should raise an error on others.
custom_params = []
custom_params << use_named_parameter('dc', options[:dc]) if options[:dc]
data = value.is_a?(String) ? value : JSON.generate(value) unless value.nil?
raw = send_put_request(@conn, ['/v1/session/create'], options, data, custom_params)
body = JSON.parse(raw.body)
body['ID']
end | ruby | def create(value = nil, options = {})
# TODO: only certain keys are recognised in a session create request,
# should raise an error on others.
custom_params = []
custom_params << use_named_parameter('dc', options[:dc]) if options[:dc]
data = value.is_a?(String) ? value : JSON.generate(value) unless value.nil?
raw = send_put_request(@conn, ['/v1/session/create'], options, data, custom_params)
body = JSON.parse(raw.body)
body['ID']
end | [
"def",
"create",
"(",
"value",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"# TODO: only certain keys are recognised in a session create request,",
"# should raise an error on others.",
"custom_params",
"=",
"[",
"]",
"custom_params",
"<<",
"use_named_parameter",
"(",
"'dc'",
",",
"options",
"[",
":dc",
"]",
")",
"if",
"options",
"[",
":dc",
"]",
"data",
"=",
"value",
".",
"is_a?",
"(",
"String",
")",
"?",
"value",
":",
"JSON",
".",
"generate",
"(",
"value",
")",
"unless",
"value",
".",
"nil?",
"raw",
"=",
"send_put_request",
"(",
"@conn",
",",
"[",
"'/v1/session/create'",
"]",
",",
"options",
",",
"data",
",",
"custom_params",
")",
"body",
"=",
"JSON",
".",
"parse",
"(",
"raw",
".",
"body",
")",
"body",
"[",
"'ID'",
"]",
"end"
] | Create a new session
@param value [Object] hash or json representation of the session arguments
@param options [Hash] session options
@return [String] The sesssion id | [
"Create",
"a",
"new",
"session"
] | cb6d06dc4ec965c30bbaf22017fd0db64b9b7677 | https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/session.rb#L10-L19 | train |
WeAreFarmGeek/diplomat | lib/diplomat/session.rb | Diplomat.Session.destroy | def destroy(id, options = {})
custom_params = []
custom_params << use_named_parameter('dc', options[:dc]) if options[:dc]
raw = send_put_request(@conn, ["/v1/session/destroy/#{id}"], options, nil, custom_params)
raw.body
end | ruby | def destroy(id, options = {})
custom_params = []
custom_params << use_named_parameter('dc', options[:dc]) if options[:dc]
raw = send_put_request(@conn, ["/v1/session/destroy/#{id}"], options, nil, custom_params)
raw.body
end | [
"def",
"destroy",
"(",
"id",
",",
"options",
"=",
"{",
"}",
")",
"custom_params",
"=",
"[",
"]",
"custom_params",
"<<",
"use_named_parameter",
"(",
"'dc'",
",",
"options",
"[",
":dc",
"]",
")",
"if",
"options",
"[",
":dc",
"]",
"raw",
"=",
"send_put_request",
"(",
"@conn",
",",
"[",
"\"/v1/session/destroy/#{id}\"",
"]",
",",
"options",
",",
"nil",
",",
"custom_params",
")",
"raw",
".",
"body",
"end"
] | Destroy a session
@param id [String] session id
@param options [Hash] session options
@return [String] Success or failure of the session destruction | [
"Destroy",
"a",
"session"
] | cb6d06dc4ec965c30bbaf22017fd0db64b9b7677 | https://github.com/WeAreFarmGeek/diplomat/blob/cb6d06dc4ec965c30bbaf22017fd0db64b9b7677/lib/diplomat/session.rb#L25-L30 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.