repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
stitchfix/merch_calendar | lib/merch_calendar/util.rb | MerchCalendar.Util.start_of_month | def start_of_month(year, month_param)
merch_month = get_merch_month_param(month_param)
retail_calendar.start_of_month(year, merch_month)
end | ruby | def start_of_month(year, month_param)
merch_month = get_merch_month_param(month_param)
retail_calendar.start_of_month(year, merch_month)
end | [
"def",
"start_of_month",
"(",
"year",
",",
"month_param",
")",
"merch_month",
"=",
"get_merch_month_param",
"(",
"month_param",
")",
"retail_calendar",
".",
"start_of_month",
"(",
"year",
",",
"merch_month",
")",
"end"
]
| The start date of the month
@example
# The following are all equivalent, and refer to May 2015
MerchCalendar.start_of_month(2015, 5)
MerchCalendar.start_of_month(2015, month: 5)
MerchCalendar.start_of_month(2015, julian_month: 5)
MerchCalendar.start_of_month(2015, merch_month: 4)
@param year [Integer] the merch year
@param month_param [Integer,Hash] an integer specifying the julian month. This can also be a named hash
@option month_param [Integer] :month the julian month
@option month_param [Integer] :julian_month the julian month
@option month_param [Integer] :merch_month the MERCH month
@return [Date] the starting date of the specified month | [
"The",
"start",
"date",
"of",
"the",
"month"
]
| b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/util.rb#L47-L50 | train |
stitchfix/merch_calendar | lib/merch_calendar/util.rb | MerchCalendar.Util.end_of_month | def end_of_month(year, month_param)
merch_month = get_merch_month_param(month_param)
retail_calendar.end_of_month(year, merch_month)
end | ruby | def end_of_month(year, month_param)
merch_month = get_merch_month_param(month_param)
retail_calendar.end_of_month(year, merch_month)
end | [
"def",
"end_of_month",
"(",
"year",
",",
"month_param",
")",
"merch_month",
"=",
"get_merch_month_param",
"(",
"month_param",
")",
"retail_calendar",
".",
"end_of_month",
"(",
"year",
",",
"merch_month",
")",
"end"
]
| The end date of the month
@param year [Integer] the merch year
@param month_param [Hash] month hash
@see #start_of_month The start_of_month method for examples using month_param
@return [Date] | [
"The",
"end",
"date",
"of",
"the",
"month"
]
| b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/util.rb#L60-L63 | train |
LeFnord/grape-starter | lib/starter/builder/base_file.rb | Starter.BaseFile.add_to_base | def add_to_base(file)
occurence = file.scan(/(\s+mount\s.*?\n)/).last.first
replacement = occurence + mount_point
file.sub!(occurence, replacement)
end | ruby | def add_to_base(file)
occurence = file.scan(/(\s+mount\s.*?\n)/).last.first
replacement = occurence + mount_point
file.sub!(occurence, replacement)
end | [
"def",
"add_to_base",
"(",
"file",
")",
"occurence",
"=",
"file",
".",
"scan",
"(",
"/",
"\\s",
"\\s",
"\\n",
"/",
")",
".",
"last",
".",
"first",
"replacement",
"=",
"occurence",
"+",
"mount_point",
"file",
".",
"sub!",
"(",
"occurence",
",",
"replacement",
")",
"end"
]
| adding mount point to base class | [
"adding",
"mount",
"point",
"to",
"base",
"class"
]
| f7c967143519e408617bba6d761a53f81b60fd6e | https://github.com/LeFnord/grape-starter/blob/f7c967143519e408617bba6d761a53f81b60fd6e/lib/starter/builder/base_file.rb#L11-L15 | train |
iZettle/ninetails | app/components/ninetails/element.rb | Ninetails.Element.valid? | def valid?
validations = properties_instances.collect do |property_type|
if property_type.property.respond_to?(:valid?)
property_type.property.valid?
else
true
end
end
validations.all?
end | ruby | def valid?
validations = properties_instances.collect do |property_type|
if property_type.property.respond_to?(:valid?)
property_type.property.valid?
else
true
end
end
validations.all?
end | [
"def",
"valid?",
"validations",
"=",
"properties_instances",
".",
"collect",
"do",
"|",
"property_type",
"|",
"if",
"property_type",
".",
"property",
".",
"respond_to?",
"(",
":valid?",
")",
"property_type",
".",
"property",
".",
"valid?",
"else",
"true",
"end",
"end",
"validations",
".",
"all?",
"end"
]
| Validate each property_type's property.
If the property_type doesn't respond to valid?, then it means it must be a
native type, or at least not something which inherits Ninetails::Property, so we will class it
as valid blindly. | [
"Validate",
"each",
"property_type",
"s",
"property",
"."
]
| a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7 | https://github.com/iZettle/ninetails/blob/a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7/app/components/ninetails/element.rb#L25-L35 | train |
iZettle/ninetails | app/models/ninetails/content_section.rb | Ninetails.ContentSection.store_settings | def store_settings(settings_hash)
settings_hash.each do |key, value|
section.public_send "#{key}=", value
end
self.settings = section.attributes
end | ruby | def store_settings(settings_hash)
settings_hash.each do |key, value|
section.public_send "#{key}=", value
end
self.settings = section.attributes
end | [
"def",
"store_settings",
"(",
"settings_hash",
")",
"settings_hash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"section",
".",
"public_send",
"\"#{key}=\"",
",",
"value",
"end",
"self",
".",
"settings",
"=",
"section",
".",
"attributes",
"end"
]
| Because the submitted data is always strings, send everything through virtus attrs so it
gets cast to the correct class.
Then, use the newly cast attributes to store in the settings json blob | [
"Because",
"the",
"submitted",
"data",
"is",
"always",
"strings",
"send",
"everything",
"through",
"virtus",
"attrs",
"so",
"it",
"gets",
"cast",
"to",
"the",
"correct",
"class",
"."
]
| a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7 | https://github.com/iZettle/ninetails/blob/a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7/app/models/ninetails/content_section.rb#L42-L48 | train |
iZettle/ninetails | app/models/ninetails/revision.rb | Ninetails.Revision.sections_are_all_valid | def sections_are_all_valid
sections.each do |section|
unless section.valid?
errors.add :base, section.errors.messages[:base]
end
end
end | ruby | def sections_are_all_valid
sections.each do |section|
unless section.valid?
errors.add :base, section.errors.messages[:base]
end
end
end | [
"def",
"sections_are_all_valid",
"sections",
".",
"each",
"do",
"|",
"section",
"|",
"unless",
"section",
".",
"valid?",
"errors",
".",
"add",
":base",
",",
"section",
".",
"errors",
".",
"messages",
"[",
":base",
"]",
"end",
"end",
"end"
]
| Validate all sections and rebuild the sections array with the instances which now
contain error messages | [
"Validate",
"all",
"sections",
"and",
"rebuild",
"the",
"sections",
"array",
"with",
"the",
"instances",
"which",
"now",
"contain",
"error",
"messages"
]
| a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7 | https://github.com/iZettle/ninetails/blob/a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7/app/models/ninetails/revision.rb#L21-L27 | train |
iZettle/ninetails | app/models/ninetails/revision.rb | Ninetails.Revision.url_is_unique | def url_is_unique
if container.is_a?(Page) && url.present?
url_exists = Ninetails::Container.
where.not(id: container.id).
includes(:current_revision).
where(ninetails_revisions: { url: url }).
exists?
errors.add :url, "is already in use" if url_exists
end
end | ruby | def url_is_unique
if container.is_a?(Page) && url.present?
url_exists = Ninetails::Container.
where.not(id: container.id).
includes(:current_revision).
where(ninetails_revisions: { url: url }).
exists?
errors.add :url, "is already in use" if url_exists
end
end | [
"def",
"url_is_unique",
"if",
"container",
".",
"is_a?",
"(",
"Page",
")",
"&&",
"url",
".",
"present?",
"url_exists",
"=",
"Ninetails",
"::",
"Container",
".",
"where",
".",
"not",
"(",
"id",
":",
"container",
".",
"id",
")",
".",
"includes",
"(",
":current_revision",
")",
".",
"where",
"(",
"ninetails_revisions",
":",
"{",
"url",
":",
"url",
"}",
")",
".",
"exists?",
"errors",
".",
"add",
":url",
",",
"\"is already in use\"",
"if",
"url_exists",
"end",
"end"
]
| Check the url is unique across revisions, but only if a container has a matching revision
set as its `current_revision`. Otherwise it'd be impossible to change one page's url
to a url which was previously used by another page in the past. | [
"Check",
"the",
"url",
"is",
"unique",
"across",
"revisions",
"but",
"only",
"if",
"a",
"container",
"has",
"a",
"matching",
"revision",
"set",
"as",
"its",
"current_revision",
".",
"Otherwise",
"it",
"d",
"be",
"impossible",
"to",
"change",
"one",
"page",
"s",
"url",
"to",
"a",
"url",
"which",
"was",
"previously",
"used",
"by",
"another",
"page",
"in",
"the",
"past",
"."
]
| a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7 | https://github.com/iZettle/ninetails/blob/a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7/app/models/ninetails/revision.rb#L42-L52 | train |
bdurand/lumberjack | lib/lumberjack/formatter.rb | Lumberjack.Formatter.add | def add(klass, formatter = nil, &block)
formatter ||= block
if formatter.is_a?(Symbol)
formatter_class_name = "#{formatter.to_s.gsub(/(^|_)([a-z])/){|m| $~[2].upcase}}Formatter"
formatter = Formatter.const_get(formatter_class_name).new
end
@class_formatters[klass] = formatter
self
end | ruby | def add(klass, formatter = nil, &block)
formatter ||= block
if formatter.is_a?(Symbol)
formatter_class_name = "#{formatter.to_s.gsub(/(^|_)([a-z])/){|m| $~[2].upcase}}Formatter"
formatter = Formatter.const_get(formatter_class_name).new
end
@class_formatters[klass] = formatter
self
end | [
"def",
"add",
"(",
"klass",
",",
"formatter",
"=",
"nil",
",",
"&",
"block",
")",
"formatter",
"||=",
"block",
"if",
"formatter",
".",
"is_a?",
"(",
"Symbol",
")",
"formatter_class_name",
"=",
"\"#{formatter.to_s.gsub(/(^|_)([a-z])/){|m| $~[2].upcase}}Formatter\"",
"formatter",
"=",
"Formatter",
".",
"const_get",
"(",
"formatter_class_name",
")",
".",
"new",
"end",
"@class_formatters",
"[",
"klass",
"]",
"=",
"formatter",
"self",
"end"
]
| Add a formatter for a class. The formatter can be specified as either an object
that responds to the +call+ method or as a symbol representing one of the predefined
formatters, or as a block to the method call.
The predefined formatters are: <tt>:inspect</tt>, <tt>:string</tt>, <tt>:exception</tt>, and <tt>:pretty_print</tt>.
=== Examples
# Use a predefined formatter
formatter.add(MyClass, :pretty_print)
# Pass in a formatter object
formatter.add(MyClass, Lumberjack::Formatter::PrettyPrintFormatter.new)
# Use a block
formatter.add(MyClass){|obj| obj.humanize}
# Add statements can be chained together
formatter.add(MyClass, :pretty_print).add(YourClass){|obj| obj.humanize} | [
"Add",
"a",
"formatter",
"for",
"a",
"class",
".",
"The",
"formatter",
"can",
"be",
"specified",
"as",
"either",
"an",
"object",
"that",
"responds",
"to",
"the",
"+",
"call",
"+",
"method",
"or",
"as",
"a",
"symbol",
"representing",
"one",
"of",
"the",
"predefined",
"formatters",
"or",
"as",
"a",
"block",
"to",
"the",
"method",
"call",
"."
]
| 04b44186433223d110dc95374851e26b888a8855 | https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/formatter.rb#L45-L53 | train |
bdurand/lumberjack | lib/lumberjack/formatter.rb | Lumberjack.Formatter.formatter_for | def formatter_for(klass) #:nodoc:
while klass != nil do
formatter = @class_formatters[klass]
return formatter if formatter
klass = klass.superclass
end
@_default_formatter
end | ruby | def formatter_for(klass) #:nodoc:
while klass != nil do
formatter = @class_formatters[klass]
return formatter if formatter
klass = klass.superclass
end
@_default_formatter
end | [
"def",
"formatter_for",
"(",
"klass",
")",
"while",
"klass",
"!=",
"nil",
"do",
"formatter",
"=",
"@class_formatters",
"[",
"klass",
"]",
"return",
"formatter",
"if",
"formatter",
"klass",
"=",
"klass",
".",
"superclass",
"end",
"@_default_formatter",
"end"
]
| Find the formatter for a class by looking it up using the class hierarchy. | [
"Find",
"the",
"formatter",
"for",
"a",
"class",
"by",
"looking",
"it",
"up",
"using",
"the",
"class",
"hierarchy",
"."
]
| 04b44186433223d110dc95374851e26b888a8855 | https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/formatter.rb#L74-L81 | train |
bdurand/lumberjack | lib/lumberjack/logger.rb | Lumberjack.Logger.add | def add(severity, message = nil, progname = nil)
severity = Severity.label_to_level(severity) if severity.is_a?(String) || severity.is_a?(Symbol)
return unless severity && severity >= level
time = Time.now
if message.nil?
if block_given?
message = yield
else
message = progname
progname = nil
end
end
message = @_formatter.format(message)
progname ||= self.progname
entry = LogEntry.new(time, severity, message, progname, $$, Lumberjack.unit_of_work_id)
begin
device.write(entry)
rescue => e
$stderr.puts("#{e.class.name}: #{e.message}#{' at ' + e.backtrace.first if e.backtrace}")
$stderr.puts(entry.to_s)
end
nil
end | ruby | def add(severity, message = nil, progname = nil)
severity = Severity.label_to_level(severity) if severity.is_a?(String) || severity.is_a?(Symbol)
return unless severity && severity >= level
time = Time.now
if message.nil?
if block_given?
message = yield
else
message = progname
progname = nil
end
end
message = @_formatter.format(message)
progname ||= self.progname
entry = LogEntry.new(time, severity, message, progname, $$, Lumberjack.unit_of_work_id)
begin
device.write(entry)
rescue => e
$stderr.puts("#{e.class.name}: #{e.message}#{' at ' + e.backtrace.first if e.backtrace}")
$stderr.puts(entry.to_s)
end
nil
end | [
"def",
"add",
"(",
"severity",
",",
"message",
"=",
"nil",
",",
"progname",
"=",
"nil",
")",
"severity",
"=",
"Severity",
".",
"label_to_level",
"(",
"severity",
")",
"if",
"severity",
".",
"is_a?",
"(",
"String",
")",
"||",
"severity",
".",
"is_a?",
"(",
"Symbol",
")",
"return",
"unless",
"severity",
"&&",
"severity",
">=",
"level",
"time",
"=",
"Time",
".",
"now",
"if",
"message",
".",
"nil?",
"if",
"block_given?",
"message",
"=",
"yield",
"else",
"message",
"=",
"progname",
"progname",
"=",
"nil",
"end",
"end",
"message",
"=",
"@_formatter",
".",
"format",
"(",
"message",
")",
"progname",
"||=",
"self",
".",
"progname",
"entry",
"=",
"LogEntry",
".",
"new",
"(",
"time",
",",
"severity",
",",
"message",
",",
"progname",
",",
"$$",
",",
"Lumberjack",
".",
"unit_of_work_id",
")",
"begin",
"device",
".",
"write",
"(",
"entry",
")",
"rescue",
"=>",
"e",
"$stderr",
".",
"puts",
"(",
"\"#{e.class.name}: #{e.message}#{' at ' + e.backtrace.first if e.backtrace}\"",
")",
"$stderr",
".",
"puts",
"(",
"entry",
".",
"to_s",
")",
"end",
"nil",
"end"
]
| Add a message to the log with a given severity. The message can be either
passed in the +message+ argument or supplied with a block. This method
is not normally called. Instead call one of the helper functions
+fatal+, +error+, +warn+, +info+, or +debug+.
The severity can be passed in either as one of the Severity constants,
or as a Severity label.
=== Example
logger.add(Lumberjack::Severity::ERROR, exception)
logger.add(Lumberjack::Severity::INFO, "Request completed")
logger.add(:warn, "Request took a long time")
logger.add(Lumberjack::Severity::DEBUG){"Start processing with options #{options.inspect}"} | [
"Add",
"a",
"message",
"to",
"the",
"log",
"with",
"a",
"given",
"severity",
".",
"The",
"message",
"can",
"be",
"either",
"passed",
"in",
"the",
"+",
"message",
"+",
"argument",
"or",
"supplied",
"with",
"a",
"block",
".",
"This",
"method",
"is",
"not",
"normally",
"called",
".",
"Instead",
"call",
"one",
"of",
"the",
"helper",
"functions",
"+",
"fatal",
"+",
"+",
"error",
"+",
"+",
"warn",
"+",
"+",
"info",
"+",
"or",
"+",
"debug",
"+",
"."
]
| 04b44186433223d110dc95374851e26b888a8855 | https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/logger.rb#L101-L127 | train |
bdurand/lumberjack | lib/lumberjack/logger.rb | Lumberjack.Logger.set_thread_local_value | def set_thread_local_value(name, value) #:nodoc:
values = Thread.current[name]
unless values
values = {}
Thread.current[name] = values
end
if value.nil?
values.delete(self)
Thread.current[name] = nil if values.empty?
else
values[self] = value
end
end | ruby | def set_thread_local_value(name, value) #:nodoc:
values = Thread.current[name]
unless values
values = {}
Thread.current[name] = values
end
if value.nil?
values.delete(self)
Thread.current[name] = nil if values.empty?
else
values[self] = value
end
end | [
"def",
"set_thread_local_value",
"(",
"name",
",",
"value",
")",
"values",
"=",
"Thread",
".",
"current",
"[",
"name",
"]",
"unless",
"values",
"values",
"=",
"{",
"}",
"Thread",
".",
"current",
"[",
"name",
"]",
"=",
"values",
"end",
"if",
"value",
".",
"nil?",
"values",
".",
"delete",
"(",
"self",
")",
"Thread",
".",
"current",
"[",
"name",
"]",
"=",
"nil",
"if",
"values",
".",
"empty?",
"else",
"values",
"[",
"self",
"]",
"=",
"value",
"end",
"end"
]
| Set a local value for a thread tied to this object. | [
"Set",
"a",
"local",
"value",
"for",
"a",
"thread",
"tied",
"to",
"this",
"object",
"."
]
| 04b44186433223d110dc95374851e26b888a8855 | https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/logger.rb#L246-L258 | train |
bdurand/lumberjack | lib/lumberjack/logger.rb | Lumberjack.Logger.push_thread_local_value | def push_thread_local_value(name, value) #:nodoc:
save_val = thread_local_value(name)
set_thread_local_value(name, value)
begin
yield
ensure
set_thread_local_value(name, save_val)
end
end | ruby | def push_thread_local_value(name, value) #:nodoc:
save_val = thread_local_value(name)
set_thread_local_value(name, value)
begin
yield
ensure
set_thread_local_value(name, save_val)
end
end | [
"def",
"push_thread_local_value",
"(",
"name",
",",
"value",
")",
"save_val",
"=",
"thread_local_value",
"(",
"name",
")",
"set_thread_local_value",
"(",
"name",
",",
"value",
")",
"begin",
"yield",
"ensure",
"set_thread_local_value",
"(",
"name",
",",
"save_val",
")",
"end",
"end"
]
| Set a local value for a thread tied to this object within a block. | [
"Set",
"a",
"local",
"value",
"for",
"a",
"thread",
"tied",
"to",
"this",
"object",
"within",
"a",
"block",
"."
]
| 04b44186433223d110dc95374851e26b888a8855 | https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/logger.rb#L267-L275 | train |
bdurand/lumberjack | lib/lumberjack/logger.rb | Lumberjack.Logger.open_device | def open_device(device, options) #:nodoc:
if device.is_a?(Device)
device
elsif device.respond_to?(:write) && device.respond_to?(:flush)
Device::Writer.new(device, options)
elsif device == :null
Device::Null.new
else
device = device.to_s
if options[:roll]
Device::DateRollingLogFile.new(device, options)
elsif options[:max_size]
Device::SizeRollingLogFile.new(device, options)
else
Device::LogFile.new(device, options)
end
end
end | ruby | def open_device(device, options) #:nodoc:
if device.is_a?(Device)
device
elsif device.respond_to?(:write) && device.respond_to?(:flush)
Device::Writer.new(device, options)
elsif device == :null
Device::Null.new
else
device = device.to_s
if options[:roll]
Device::DateRollingLogFile.new(device, options)
elsif options[:max_size]
Device::SizeRollingLogFile.new(device, options)
else
Device::LogFile.new(device, options)
end
end
end | [
"def",
"open_device",
"(",
"device",
",",
"options",
")",
"if",
"device",
".",
"is_a?",
"(",
"Device",
")",
"device",
"elsif",
"device",
".",
"respond_to?",
"(",
":write",
")",
"&&",
"device",
".",
"respond_to?",
"(",
":flush",
")",
"Device",
"::",
"Writer",
".",
"new",
"(",
"device",
",",
"options",
")",
"elsif",
"device",
"==",
":null",
"Device",
"::",
"Null",
".",
"new",
"else",
"device",
"=",
"device",
".",
"to_s",
"if",
"options",
"[",
":roll",
"]",
"Device",
"::",
"DateRollingLogFile",
".",
"new",
"(",
"device",
",",
"options",
")",
"elsif",
"options",
"[",
":max_size",
"]",
"Device",
"::",
"SizeRollingLogFile",
".",
"new",
"(",
"device",
",",
"options",
")",
"else",
"Device",
"::",
"LogFile",
".",
"new",
"(",
"device",
",",
"options",
")",
"end",
"end",
"end"
]
| Open a logging device. | [
"Open",
"a",
"logging",
"device",
"."
]
| 04b44186433223d110dc95374851e26b888a8855 | https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/logger.rb#L278-L295 | train |
bdurand/lumberjack | lib/lumberjack/logger.rb | Lumberjack.Logger.create_flusher_thread | def create_flusher_thread(flush_seconds) #:nodoc:
if flush_seconds > 0
begin
logger = self
Thread.new do
loop do
begin
sleep(flush_seconds)
logger.flush if Time.now - logger.last_flushed_at >= flush_seconds
rescue => e
STDERR.puts("Error flushing log: #{e.inspect}")
end
end
end
end
end
end | ruby | def create_flusher_thread(flush_seconds) #:nodoc:
if flush_seconds > 0
begin
logger = self
Thread.new do
loop do
begin
sleep(flush_seconds)
logger.flush if Time.now - logger.last_flushed_at >= flush_seconds
rescue => e
STDERR.puts("Error flushing log: #{e.inspect}")
end
end
end
end
end
end | [
"def",
"create_flusher_thread",
"(",
"flush_seconds",
")",
"if",
"flush_seconds",
">",
"0",
"begin",
"logger",
"=",
"self",
"Thread",
".",
"new",
"do",
"loop",
"do",
"begin",
"sleep",
"(",
"flush_seconds",
")",
"logger",
".",
"flush",
"if",
"Time",
".",
"now",
"-",
"logger",
".",
"last_flushed_at",
">=",
"flush_seconds",
"rescue",
"=>",
"e",
"STDERR",
".",
"puts",
"(",
"\"Error flushing log: #{e.inspect}\"",
")",
"end",
"end",
"end",
"end",
"end",
"end"
]
| Create a thread that will periodically call flush. | [
"Create",
"a",
"thread",
"that",
"will",
"periodically",
"call",
"flush",
"."
]
| 04b44186433223d110dc95374851e26b888a8855 | https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/logger.rb#L298-L314 | train |
bdurand/lumberjack | lib/lumberjack/template.rb | Lumberjack.Template.compile | def compile(template) #:nodoc:
template.gsub(/:[a-z0-9_]+/) do |match|
position = TEMPLATE_ARGUMENT_ORDER.index(match)
if position
"%#{position + 1}$s"
else
match
end
end
end | ruby | def compile(template) #:nodoc:
template.gsub(/:[a-z0-9_]+/) do |match|
position = TEMPLATE_ARGUMENT_ORDER.index(match)
if position
"%#{position + 1}$s"
else
match
end
end
end | [
"def",
"compile",
"(",
"template",
")",
"template",
".",
"gsub",
"(",
"/",
"/",
")",
"do",
"|",
"match",
"|",
"position",
"=",
"TEMPLATE_ARGUMENT_ORDER",
".",
"index",
"(",
"match",
")",
"if",
"position",
"\"%#{position + 1}$s\"",
"else",
"match",
"end",
"end",
"end"
]
| Compile the template string into a value that can be used with sprintf. | [
"Compile",
"the",
"template",
"string",
"into",
"a",
"value",
"that",
"can",
"be",
"used",
"with",
"sprintf",
"."
]
| 04b44186433223d110dc95374851e26b888a8855 | https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/template.rb#L62-L71 | train |
theforeman/foreman_fog_proxmox | app/models/foreman_fog_proxmox/proxmox.rb | ForemanFogProxmox.Proxmox.vm_compute_attributes | def vm_compute_attributes(vm)
vm_attrs = vm.attributes.reject { |key,value| [:config, :vmid].include?(key.to_sym) || value.to_s.empty? }
vm_attrs = set_vm_config_attributes(vm, vm_attrs)
vm_attrs = set_vm_volumes_attributes(vm, vm_attrs)
vm_attrs = set_vm_interfaces_attributes(vm, vm_attrs)
vm_attrs
end | ruby | def vm_compute_attributes(vm)
vm_attrs = vm.attributes.reject { |key,value| [:config, :vmid].include?(key.to_sym) || value.to_s.empty? }
vm_attrs = set_vm_config_attributes(vm, vm_attrs)
vm_attrs = set_vm_volumes_attributes(vm, vm_attrs)
vm_attrs = set_vm_interfaces_attributes(vm, vm_attrs)
vm_attrs
end | [
"def",
"vm_compute_attributes",
"(",
"vm",
")",
"vm_attrs",
"=",
"vm",
".",
"attributes",
".",
"reject",
"{",
"|",
"key",
",",
"value",
"|",
"[",
":config",
",",
":vmid",
"]",
".",
"include?",
"(",
"key",
".",
"to_sym",
")",
"||",
"value",
".",
"to_s",
".",
"empty?",
"}",
"vm_attrs",
"=",
"set_vm_config_attributes",
"(",
"vm",
",",
"vm_attrs",
")",
"vm_attrs",
"=",
"set_vm_volumes_attributes",
"(",
"vm",
",",
"vm_attrs",
")",
"vm_attrs",
"=",
"set_vm_interfaces_attributes",
"(",
"vm",
",",
"vm_attrs",
")",
"vm_attrs",
"end"
]
| used by host.clone | [
"used",
"by",
"host",
".",
"clone"
]
| 62319d08ddd95f9e34a1a33b999428c05d5c4a5e | https://github.com/theforeman/foreman_fog_proxmox/blob/62319d08ddd95f9e34a1a33b999428c05d5c4a5e/app/models/foreman_fog_proxmox/proxmox.rb#L191-L197 | train |
sporkmonger/uuidtools | lib/uuidtools.rb | UUIDTools.UUID.timestamp | def timestamp
return nil if self.version != 1
gmt_timestamp_100_nanoseconds = 0
gmt_timestamp_100_nanoseconds +=
((self.time_hi_and_version & 0x0FFF) << 48)
gmt_timestamp_100_nanoseconds += (self.time_mid << 32)
gmt_timestamp_100_nanoseconds += self.time_low
return Time.at(
(gmt_timestamp_100_nanoseconds - 0x01B21DD213814000) / 10000000.0)
end | ruby | def timestamp
return nil if self.version != 1
gmt_timestamp_100_nanoseconds = 0
gmt_timestamp_100_nanoseconds +=
((self.time_hi_and_version & 0x0FFF) << 48)
gmt_timestamp_100_nanoseconds += (self.time_mid << 32)
gmt_timestamp_100_nanoseconds += self.time_low
return Time.at(
(gmt_timestamp_100_nanoseconds - 0x01B21DD213814000) / 10000000.0)
end | [
"def",
"timestamp",
"return",
"nil",
"if",
"self",
".",
"version",
"!=",
"1",
"gmt_timestamp_100_nanoseconds",
"=",
"0",
"gmt_timestamp_100_nanoseconds",
"+=",
"(",
"(",
"self",
".",
"time_hi_and_version",
"&",
"0x0FFF",
")",
"<<",
"48",
")",
"gmt_timestamp_100_nanoseconds",
"+=",
"(",
"self",
".",
"time_mid",
"<<",
"32",
")",
"gmt_timestamp_100_nanoseconds",
"+=",
"self",
".",
"time_low",
"return",
"Time",
".",
"at",
"(",
"(",
"gmt_timestamp_100_nanoseconds",
"-",
"0x01B21DD213814000",
")",
"/",
"10000000.0",
")",
"end"
]
| Returns the timestamp used to generate this UUID | [
"Returns",
"the",
"timestamp",
"used",
"to",
"generate",
"this",
"UUID"
]
| a10724236cefd922ee5cd3de7695fb6e5fd703f5 | https://github.com/sporkmonger/uuidtools/blob/a10724236cefd922ee5cd3de7695fb6e5fd703f5/lib/uuidtools.rb#L382-L391 | train |
sporkmonger/uuidtools | lib/uuidtools.rb | UUIDTools.UUID.generate_s | def generate_s
result = sprintf("%8.8x-%4.4x-%4.4x-%2.2x%2.2x-", @time_low, @time_mid,
@time_hi_and_version, @clock_seq_hi_and_reserved, @clock_seq_low);
6.times do |i|
result << sprintf("%2.2x", @nodes[i])
end
return result.downcase
end | ruby | def generate_s
result = sprintf("%8.8x-%4.4x-%4.4x-%2.2x%2.2x-", @time_low, @time_mid,
@time_hi_and_version, @clock_seq_hi_and_reserved, @clock_seq_low);
6.times do |i|
result << sprintf("%2.2x", @nodes[i])
end
return result.downcase
end | [
"def",
"generate_s",
"result",
"=",
"sprintf",
"(",
"\"%8.8x-%4.4x-%4.4x-%2.2x%2.2x-\"",
",",
"@time_low",
",",
"@time_mid",
",",
"@time_hi_and_version",
",",
"@clock_seq_hi_and_reserved",
",",
"@clock_seq_low",
")",
";",
"6",
".",
"times",
"do",
"|",
"i",
"|",
"result",
"<<",
"sprintf",
"(",
"\"%2.2x\"",
",",
"@nodes",
"[",
"i",
"]",
")",
"end",
"return",
"result",
".",
"downcase",
"end"
]
| Generates a string representation for this UUID.
@api private | [
"Generates",
"a",
"string",
"representation",
"for",
"this",
"UUID",
"."
]
| a10724236cefd922ee5cd3de7695fb6e5fd703f5 | https://github.com/sporkmonger/uuidtools/blob/a10724236cefd922ee5cd3de7695fb6e5fd703f5/lib/uuidtools.rb#L500-L507 | train |
lostisland/sawyer | lib/sawyer/resource.rb | Sawyer.Resource.process_value | def process_value(value)
case value
when Hash then self.class.new(@_agent, value)
when Array then value.map { |v| process_value(v) }
else value
end
end | ruby | def process_value(value)
case value
when Hash then self.class.new(@_agent, value)
when Array then value.map { |v| process_value(v) }
else value
end
end | [
"def",
"process_value",
"(",
"value",
")",
"case",
"value",
"when",
"Hash",
"then",
"self",
".",
"class",
".",
"new",
"(",
"@_agent",
",",
"value",
")",
"when",
"Array",
"then",
"value",
".",
"map",
"{",
"|",
"v",
"|",
"process_value",
"(",
"v",
")",
"}",
"else",
"value",
"end",
"end"
]
| Initializes a Resource with the given data.
agent - The Sawyer::Agent that made the API request.
data - Hash of key/value properties.
Processes an individual value of this resource. Hashes get exploded
into another Resource, and Arrays get their values processed too.
value - An Object value of a Resource's data.
Returns an Object to set as the value of a Resource key. | [
"Initializes",
"a",
"Resource",
"with",
"the",
"given",
"data",
"."
]
| a541a68be349a7982e24b80d94fe380a37b4805c | https://github.com/lostisland/sawyer/blob/a541a68be349a7982e24b80d94fe380a37b4805c/lib/sawyer/resource.rb#L32-L38 | train |
lostisland/sawyer | lib/sawyer/resource.rb | Sawyer.Resource.method_missing | def method_missing(method, *args)
attr_name, suffix = method.to_s.scan(/([a-z0-9\_]+)(\?|\=)?$/i).first
if suffix == ATTR_SETTER
@_metaclass.send(:attr_accessor, attr_name)
@_fields << attr_name.to_sym
send(method, args.first)
elsif attr_name && @_fields.include?(attr_name.to_sym)
value = @attrs[attr_name.to_sym]
case suffix
when nil
@_metaclass.send(:attr_accessor, attr_name)
value
when ATTR_PREDICATE then !!value
end
elsif suffix.nil? && SPECIAL_METHODS.include?(attr_name)
instance_variable_get "@_#{attr_name}"
elsif attr_name && !@_fields.include?(attr_name.to_sym)
nil
else
super
end
end | ruby | def method_missing(method, *args)
attr_name, suffix = method.to_s.scan(/([a-z0-9\_]+)(\?|\=)?$/i).first
if suffix == ATTR_SETTER
@_metaclass.send(:attr_accessor, attr_name)
@_fields << attr_name.to_sym
send(method, args.first)
elsif attr_name && @_fields.include?(attr_name.to_sym)
value = @attrs[attr_name.to_sym]
case suffix
when nil
@_metaclass.send(:attr_accessor, attr_name)
value
when ATTR_PREDICATE then !!value
end
elsif suffix.nil? && SPECIAL_METHODS.include?(attr_name)
instance_variable_get "@_#{attr_name}"
elsif attr_name && !@_fields.include?(attr_name.to_sym)
nil
else
super
end
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
")",
"attr_name",
",",
"suffix",
"=",
"method",
".",
"to_s",
".",
"scan",
"(",
"/",
"\\_",
"\\?",
"\\=",
"/i",
")",
".",
"first",
"if",
"suffix",
"==",
"ATTR_SETTER",
"@_metaclass",
".",
"send",
"(",
":attr_accessor",
",",
"attr_name",
")",
"@_fields",
"<<",
"attr_name",
".",
"to_sym",
"send",
"(",
"method",
",",
"args",
".",
"first",
")",
"elsif",
"attr_name",
"&&",
"@_fields",
".",
"include?",
"(",
"attr_name",
".",
"to_sym",
")",
"value",
"=",
"@attrs",
"[",
"attr_name",
".",
"to_sym",
"]",
"case",
"suffix",
"when",
"nil",
"@_metaclass",
".",
"send",
"(",
":attr_accessor",
",",
"attr_name",
")",
"value",
"when",
"ATTR_PREDICATE",
"then",
"!",
"!",
"value",
"end",
"elsif",
"suffix",
".",
"nil?",
"&&",
"SPECIAL_METHODS",
".",
"include?",
"(",
"attr_name",
")",
"instance_variable_get",
"\"@_#{attr_name}\"",
"elsif",
"attr_name",
"&&",
"!",
"@_fields",
".",
"include?",
"(",
"attr_name",
".",
"to_sym",
")",
"nil",
"else",
"super",
"end",
"end"
]
| Provides access to a resource's attributes. | [
"Provides",
"access",
"to",
"a",
"resource",
"s",
"attributes",
"."
]
| a541a68be349a7982e24b80d94fe380a37b4805c | https://github.com/lostisland/sawyer/blob/a541a68be349a7982e24b80d94fe380a37b4805c/lib/sawyer/resource.rb#L76-L97 | train |
lostisland/sawyer | lib/sawyer/agent.rb | Sawyer.Agent.call | def call(method, url, data = nil, options = nil)
if NO_BODY.include?(method)
options ||= data
data = nil
end
options ||= {}
url = expand_url(url, options[:uri])
started = nil
res = @conn.send method, url do |req|
if data
req.body = data.is_a?(String) ? data : encode_body(data)
end
if params = options[:query]
req.params.update params
end
if headers = options[:headers]
req.headers.update headers
end
started = Time.now
end
Response.new self, res, :sawyer_started => started, :sawyer_ended => Time.now
end | ruby | def call(method, url, data = nil, options = nil)
if NO_BODY.include?(method)
options ||= data
data = nil
end
options ||= {}
url = expand_url(url, options[:uri])
started = nil
res = @conn.send method, url do |req|
if data
req.body = data.is_a?(String) ? data : encode_body(data)
end
if params = options[:query]
req.params.update params
end
if headers = options[:headers]
req.headers.update headers
end
started = Time.now
end
Response.new self, res, :sawyer_started => started, :sawyer_ended => Time.now
end | [
"def",
"call",
"(",
"method",
",",
"url",
",",
"data",
"=",
"nil",
",",
"options",
"=",
"nil",
")",
"if",
"NO_BODY",
".",
"include?",
"(",
"method",
")",
"options",
"||=",
"data",
"data",
"=",
"nil",
"end",
"options",
"||=",
"{",
"}",
"url",
"=",
"expand_url",
"(",
"url",
",",
"options",
"[",
":uri",
"]",
")",
"started",
"=",
"nil",
"res",
"=",
"@conn",
".",
"send",
"method",
",",
"url",
"do",
"|",
"req",
"|",
"if",
"data",
"req",
".",
"body",
"=",
"data",
".",
"is_a?",
"(",
"String",
")",
"?",
"data",
":",
"encode_body",
"(",
"data",
")",
"end",
"if",
"params",
"=",
"options",
"[",
":query",
"]",
"req",
".",
"params",
".",
"update",
"params",
"end",
"if",
"headers",
"=",
"options",
"[",
":headers",
"]",
"req",
".",
"headers",
".",
"update",
"headers",
"end",
"started",
"=",
"Time",
".",
"now",
"end",
"Response",
".",
"new",
"self",
",",
"res",
",",
":sawyer_started",
"=>",
"started",
",",
":sawyer_ended",
"=>",
"Time",
".",
"now",
"end"
]
| Makes a request through Faraday.
method - The Symbol name of an HTTP method.
url - The String URL to access. This can be relative to the Agent's
endpoint.
data - The Optional Hash or Resource body to be sent. :get or :head
requests can have no body, so this can be the options Hash
instead.
options - Hash of option to configure the API request.
:headers - Hash of API headers to set.
:query - Hash of URL query params to set.
Returns a Sawyer::Response. | [
"Makes",
"a",
"request",
"through",
"Faraday",
"."
]
| a541a68be349a7982e24b80d94fe380a37b4805c | https://github.com/lostisland/sawyer/blob/a541a68be349a7982e24b80d94fe380a37b4805c/lib/sawyer/agent.rb#L85-L108 | train |
lostisland/sawyer | lib/sawyer/response.rb | Sawyer.Response.process_data | def process_data(data)
case data
when Hash then Resource.new(agent, data)
when Array then data.map { |hash| process_data(hash) }
when nil then nil
else data
end
end | ruby | def process_data(data)
case data
when Hash then Resource.new(agent, data)
when Array then data.map { |hash| process_data(hash) }
when nil then nil
else data
end
end | [
"def",
"process_data",
"(",
"data",
")",
"case",
"data",
"when",
"Hash",
"then",
"Resource",
".",
"new",
"(",
"agent",
",",
"data",
")",
"when",
"Array",
"then",
"data",
".",
"map",
"{",
"|",
"hash",
"|",
"process_data",
"(",
"hash",
")",
"}",
"when",
"nil",
"then",
"nil",
"else",
"data",
"end",
"end"
]
| Turns parsed contents from an API response into a Resource or
collection of Resources.
data - Either an Array or Hash parsed from JSON.
Returns either a Resource or Array of Resources. | [
"Turns",
"parsed",
"contents",
"from",
"an",
"API",
"response",
"into",
"a",
"Resource",
"or",
"collection",
"of",
"Resources",
"."
]
| a541a68be349a7982e24b80d94fe380a37b4805c | https://github.com/lostisland/sawyer/blob/a541a68be349a7982e24b80d94fe380a37b4805c/lib/sawyer/response.rb#L38-L45 | train |
lostisland/sawyer | lib/sawyer/response.rb | Sawyer.Response.process_rels | def process_rels
links = ( @headers["Link"] || "" ).split(', ').map do |link|
href, name = link.match(/<(.*?)>; rel="(\w+)"/).captures
[name.to_sym, Relation.from_link(@agent, name, :href => href)]
end
Hash[*links.flatten]
end | ruby | def process_rels
links = ( @headers["Link"] || "" ).split(', ').map do |link|
href, name = link.match(/<(.*?)>; rel="(\w+)"/).captures
[name.to_sym, Relation.from_link(@agent, name, :href => href)]
end
Hash[*links.flatten]
end | [
"def",
"process_rels",
"links",
"=",
"(",
"@headers",
"[",
"\"Link\"",
"]",
"||",
"\"\"",
")",
".",
"split",
"(",
"', '",
")",
".",
"map",
"do",
"|",
"link",
"|",
"href",
",",
"name",
"=",
"link",
".",
"match",
"(",
"/",
"\\w",
"/",
")",
".",
"captures",
"[",
"name",
".",
"to_sym",
",",
"Relation",
".",
"from_link",
"(",
"@agent",
",",
"name",
",",
":href",
"=>",
"href",
")",
"]",
"end",
"Hash",
"[",
"*",
"links",
".",
"flatten",
"]",
"end"
]
| Finds link relations from 'Link' response header
Returns an array of Relations | [
"Finds",
"link",
"relations",
"from",
"Link",
"response",
"header"
]
| a541a68be349a7982e24b80d94fe380a37b4805c | https://github.com/lostisland/sawyer/blob/a541a68be349a7982e24b80d94fe380a37b4805c/lib/sawyer/response.rb#L50-L58 | train |
mdp/gibberish | lib/gibberish/aes.rb | Gibberish.AES::SJCL.check_cipher_options | def check_cipher_options(c_opts)
if @opts[:max_iter] < c_opts[:iter]
# Prevent DOS attacks from high PBKDF iterations
# You an increase this by passing in opts[:max_iter]
raise CipherOptionsError.new("Iteration count of #{c_opts[:iter]} exceeds the maximum of #{@opts[:max_iter]}")
elsif !ALLOWED_MODES.include?(c_opts[:mode])
raise CipherOptionsError.new("Mode '#{c_opts[:mode]}' not supported")
elsif !ALLOWED_KS.include?(c_opts[:ks])
raise CipherOptionsError.new("Keystrength of #{c_opts[:ks]} not supported")
elsif !ALLOWED_TS.include?(c_opts[:ts])
raise CipherOptionsError.new("Tag length of #{c_opts[:ts]} not supported")
elsif c_opts[:iv] && Base64.decode64(c_opts[:iv]).length > 12
raise CipherOptionsError.new("Initialization vector's greater than 12 bytes are not supported in Ruby.")
end
end | ruby | def check_cipher_options(c_opts)
if @opts[:max_iter] < c_opts[:iter]
# Prevent DOS attacks from high PBKDF iterations
# You an increase this by passing in opts[:max_iter]
raise CipherOptionsError.new("Iteration count of #{c_opts[:iter]} exceeds the maximum of #{@opts[:max_iter]}")
elsif !ALLOWED_MODES.include?(c_opts[:mode])
raise CipherOptionsError.new("Mode '#{c_opts[:mode]}' not supported")
elsif !ALLOWED_KS.include?(c_opts[:ks])
raise CipherOptionsError.new("Keystrength of #{c_opts[:ks]} not supported")
elsif !ALLOWED_TS.include?(c_opts[:ts])
raise CipherOptionsError.new("Tag length of #{c_opts[:ts]} not supported")
elsif c_opts[:iv] && Base64.decode64(c_opts[:iv]).length > 12
raise CipherOptionsError.new("Initialization vector's greater than 12 bytes are not supported in Ruby.")
end
end | [
"def",
"check_cipher_options",
"(",
"c_opts",
")",
"if",
"@opts",
"[",
":max_iter",
"]",
"<",
"c_opts",
"[",
":iter",
"]",
"raise",
"CipherOptionsError",
".",
"new",
"(",
"\"Iteration count of #{c_opts[:iter]} exceeds the maximum of #{@opts[:max_iter]}\"",
")",
"elsif",
"!",
"ALLOWED_MODES",
".",
"include?",
"(",
"c_opts",
"[",
":mode",
"]",
")",
"raise",
"CipherOptionsError",
".",
"new",
"(",
"\"Mode '#{c_opts[:mode]}' not supported\"",
")",
"elsif",
"!",
"ALLOWED_KS",
".",
"include?",
"(",
"c_opts",
"[",
":ks",
"]",
")",
"raise",
"CipherOptionsError",
".",
"new",
"(",
"\"Keystrength of #{c_opts[:ks]} not supported\"",
")",
"elsif",
"!",
"ALLOWED_TS",
".",
"include?",
"(",
"c_opts",
"[",
":ts",
"]",
")",
"raise",
"CipherOptionsError",
".",
"new",
"(",
"\"Tag length of #{c_opts[:ts]} not supported\"",
")",
"elsif",
"c_opts",
"[",
":iv",
"]",
"&&",
"Base64",
".",
"decode64",
"(",
"c_opts",
"[",
":iv",
"]",
")",
".",
"length",
">",
"12",
"raise",
"CipherOptionsError",
".",
"new",
"(",
"\"Initialization vector's greater than 12 bytes are not supported in Ruby.\"",
")",
"end",
"end"
]
| Assume the worst | [
"Assume",
"the",
"worst"
]
| 707bfc1f6c4ab17df8a980a9e2b80970768a41c6 | https://github.com/mdp/gibberish/blob/707bfc1f6c4ab17df8a980a9e2b80970768a41c6/lib/gibberish/aes.rb#L190-L204 | train |
mdp/gibberish | lib/gibberish/aes.rb | Gibberish.AES::CBC.encrypt | def encrypt(data, opts={})
salt = generate_salt(opts[:salt])
setup_cipher(:encrypt, salt)
e = cipher.update(data) + cipher.final
e = "Salted__#{salt}#{e}" #OpenSSL compatible
opts[:binary] ? e : Base64.encode64(e)
end | ruby | def encrypt(data, opts={})
salt = generate_salt(opts[:salt])
setup_cipher(:encrypt, salt)
e = cipher.update(data) + cipher.final
e = "Salted__#{salt}#{e}" #OpenSSL compatible
opts[:binary] ? e : Base64.encode64(e)
end | [
"def",
"encrypt",
"(",
"data",
",",
"opts",
"=",
"{",
"}",
")",
"salt",
"=",
"generate_salt",
"(",
"opts",
"[",
":salt",
"]",
")",
"setup_cipher",
"(",
":encrypt",
",",
"salt",
")",
"e",
"=",
"cipher",
".",
"update",
"(",
"data",
")",
"+",
"cipher",
".",
"final",
"e",
"=",
"\"Salted__#{salt}#{e}\"",
"opts",
"[",
":binary",
"]",
"?",
"e",
":",
"Base64",
".",
"encode64",
"(",
"e",
")",
"end"
]
| Initialize with the password
@param [String] password
@param [Integer] size
@param [String] mode | [
"Initialize",
"with",
"the",
"password"
]
| 707bfc1f6c4ab17df8a980a9e2b80970768a41c6 | https://github.com/mdp/gibberish/blob/707bfc1f6c4ab17df8a980a9e2b80970768a41c6/lib/gibberish/aes.rb#L225-L231 | train |
mdp/gibberish | lib/gibberish/rsa.rb | Gibberish.RSA.encrypt | def encrypt(data, opts={})
data = data.to_s
enc = @key.public_encrypt(data)
if opts[:binary]
enc
else
Base64.encode64(enc)
end
end | ruby | def encrypt(data, opts={})
data = data.to_s
enc = @key.public_encrypt(data)
if opts[:binary]
enc
else
Base64.encode64(enc)
end
end | [
"def",
"encrypt",
"(",
"data",
",",
"opts",
"=",
"{",
"}",
")",
"data",
"=",
"data",
".",
"to_s",
"enc",
"=",
"@key",
".",
"public_encrypt",
"(",
"data",
")",
"if",
"opts",
"[",
":binary",
"]",
"enc",
"else",
"Base64",
".",
"encode64",
"(",
"enc",
")",
"end",
"end"
]
| Expects a public key at the minumum
@param [#to_s] key public or private
@param [String] passphrase to key
Encrypt data using the key
@param [#to_s] data
@param [Hash] opts
@option opts [Boolean] :binary (false) encode the data in binary, not Base64 | [
"Expects",
"a",
"public",
"key",
"at",
"the",
"minumum"
]
| 707bfc1f6c4ab17df8a980a9e2b80970768a41c6 | https://github.com/mdp/gibberish/blob/707bfc1f6c4ab17df8a980a9e2b80970768a41c6/lib/gibberish/rsa.rb#L87-L95 | train |
mdp/gibberish | lib/gibberish/rsa.rb | Gibberish.RSA.decrypt | def decrypt(data, opts={})
data = data.to_s
raise "No private key set!" unless @key.private?
unless opts[:binary]
data = Base64.decode64(data)
end
@key.private_decrypt(data)
end | ruby | def decrypt(data, opts={})
data = data.to_s
raise "No private key set!" unless @key.private?
unless opts[:binary]
data = Base64.decode64(data)
end
@key.private_decrypt(data)
end | [
"def",
"decrypt",
"(",
"data",
",",
"opts",
"=",
"{",
"}",
")",
"data",
"=",
"data",
".",
"to_s",
"raise",
"\"No private key set!\"",
"unless",
"@key",
".",
"private?",
"unless",
"opts",
"[",
":binary",
"]",
"data",
"=",
"Base64",
".",
"decode64",
"(",
"data",
")",
"end",
"@key",
".",
"private_decrypt",
"(",
"data",
")",
"end"
]
| Decrypt data using the key
@param [#to_s] data
@param [Hash] opts
@option opts [Boolean] :binary (false) don't decode the data as Base64 | [
"Decrypt",
"data",
"using",
"the",
"key"
]
| 707bfc1f6c4ab17df8a980a9e2b80970768a41c6 | https://github.com/mdp/gibberish/blob/707bfc1f6c4ab17df8a980a9e2b80970768a41c6/lib/gibberish/rsa.rb#L102-L109 | train |
fabrik42/acts_as_api | lib/acts_as_api/base.rb | ActsAsApi.Base.acts_as_api | def acts_as_api
class_eval do
include ActsAsApi::Base::InstanceMethods
extend ActsAsApi::Base::ClassMethods
end
if block_given?
yield ActsAsApi::Config
end
end | ruby | def acts_as_api
class_eval do
include ActsAsApi::Base::InstanceMethods
extend ActsAsApi::Base::ClassMethods
end
if block_given?
yield ActsAsApi::Config
end
end | [
"def",
"acts_as_api",
"class_eval",
"do",
"include",
"ActsAsApi",
"::",
"Base",
"::",
"InstanceMethods",
"extend",
"ActsAsApi",
"::",
"Base",
"::",
"ClassMethods",
"end",
"if",
"block_given?",
"yield",
"ActsAsApi",
"::",
"Config",
"end",
"end"
]
| When invoked, it enriches the current model with the
class and instance methods to act as api. | [
"When",
"invoked",
"it",
"enriches",
"the",
"current",
"model",
"with",
"the",
"class",
"and",
"instance",
"methods",
"to",
"act",
"as",
"api",
"."
]
| 874ccfbcd5efcd90b6b56ec126b07c053675901e | https://github.com/fabrik42/acts_as_api/blob/874ccfbcd5efcd90b6b56ec126b07c053675901e/lib/acts_as_api/base.rb#L12-L21 | train |
fabrik42/acts_as_api | lib/acts_as_api/api_template.rb | ActsAsApi.ApiTemplate.add | def add(val, options = {})
item_key = (options[:as] || val).to_sym
self[item_key] = val
@options[item_key] = options
end | ruby | def add(val, options = {})
item_key = (options[:as] || val).to_sym
self[item_key] = val
@options[item_key] = options
end | [
"def",
"add",
"(",
"val",
",",
"options",
"=",
"{",
"}",
")",
"item_key",
"=",
"(",
"options",
"[",
":as",
"]",
"||",
"val",
")",
".",
"to_sym",
"self",
"[",
"item_key",
"]",
"=",
"val",
"@options",
"[",
"item_key",
"]",
"=",
"options",
"end"
]
| Adds a field to the api template
The value passed can be one of the following:
* Symbol - the method with the same name will be called on the model when rendering.
* String - must be in the form "method1.method2.method3", will call this method chain.
* Hash - will be added as a sub hash and all its items will be resolved the way described above.
Possible options to pass:
* :template - Determine the template that should be used to render the item if it is
+api_accessible+ itself. | [
"Adds",
"a",
"field",
"to",
"the",
"api",
"template"
]
| 874ccfbcd5efcd90b6b56ec126b07c053675901e | https://github.com/fabrik42/acts_as_api/blob/874ccfbcd5efcd90b6b56ec126b07c053675901e/lib/acts_as_api/api_template.rb#L36-L42 | train |
fabrik42/acts_as_api | lib/acts_as_api/api_template.rb | ActsAsApi.ApiTemplate.allowed_to_render? | def allowed_to_render?(fieldset, field, model, options)
return true unless fieldset.is_a? ActsAsApi::ApiTemplate
fieldset_options = fieldset.options_for(field)
if fieldset_options[:unless]
!(condition_fulfilled?(model, fieldset_options[:unless], options))
elsif fieldset_options[:if]
condition_fulfilled?(model, fieldset_options[:if], options)
else
true
end
end | ruby | def allowed_to_render?(fieldset, field, model, options)
return true unless fieldset.is_a? ActsAsApi::ApiTemplate
fieldset_options = fieldset.options_for(field)
if fieldset_options[:unless]
!(condition_fulfilled?(model, fieldset_options[:unless], options))
elsif fieldset_options[:if]
condition_fulfilled?(model, fieldset_options[:if], options)
else
true
end
end | [
"def",
"allowed_to_render?",
"(",
"fieldset",
",",
"field",
",",
"model",
",",
"options",
")",
"return",
"true",
"unless",
"fieldset",
".",
"is_a?",
"ActsAsApi",
"::",
"ApiTemplate",
"fieldset_options",
"=",
"fieldset",
".",
"options_for",
"(",
"field",
")",
"if",
"fieldset_options",
"[",
":unless",
"]",
"!",
"(",
"condition_fulfilled?",
"(",
"model",
",",
"fieldset_options",
"[",
":unless",
"]",
",",
"options",
")",
")",
"elsif",
"fieldset_options",
"[",
":if",
"]",
"condition_fulfilled?",
"(",
"model",
",",
"fieldset_options",
"[",
":if",
"]",
",",
"options",
")",
"else",
"true",
"end",
"end"
]
| Decides if the passed item should be added to
the response based on the conditional options passed. | [
"Decides",
"if",
"the",
"passed",
"item",
"should",
"be",
"added",
"to",
"the",
"response",
"based",
"on",
"the",
"conditional",
"options",
"passed",
"."
]
| 874ccfbcd5efcd90b6b56ec126b07c053675901e | https://github.com/fabrik42/acts_as_api/blob/874ccfbcd5efcd90b6b56ec126b07c053675901e/lib/acts_as_api/api_template.rb#L67-L79 | train |
fabrik42/acts_as_api | lib/acts_as_api/api_template.rb | ActsAsApi.ApiTemplate.to_response_hash | def to_response_hash(model, fieldset = self, options = {})
api_output = {}
fieldset.each do |field, value|
next unless allowed_to_render?(fieldset, field, model, options)
out = process_value(model, value, options)
if out.respond_to?(:as_api_response)
sub_template = api_template_for(fieldset, field)
out = out.as_api_response(sub_template, options)
end
api_output[field] = out
end
api_output
end | ruby | def to_response_hash(model, fieldset = self, options = {})
api_output = {}
fieldset.each do |field, value|
next unless allowed_to_render?(fieldset, field, model, options)
out = process_value(model, value, options)
if out.respond_to?(:as_api_response)
sub_template = api_template_for(fieldset, field)
out = out.as_api_response(sub_template, options)
end
api_output[field] = out
end
api_output
end | [
"def",
"to_response_hash",
"(",
"model",
",",
"fieldset",
"=",
"self",
",",
"options",
"=",
"{",
"}",
")",
"api_output",
"=",
"{",
"}",
"fieldset",
".",
"each",
"do",
"|",
"field",
",",
"value",
"|",
"next",
"unless",
"allowed_to_render?",
"(",
"fieldset",
",",
"field",
",",
"model",
",",
"options",
")",
"out",
"=",
"process_value",
"(",
"model",
",",
"value",
",",
"options",
")",
"if",
"out",
".",
"respond_to?",
"(",
":as_api_response",
")",
"sub_template",
"=",
"api_template_for",
"(",
"fieldset",
",",
"field",
")",
"out",
"=",
"out",
".",
"as_api_response",
"(",
"sub_template",
",",
"options",
")",
"end",
"api_output",
"[",
"field",
"]",
"=",
"out",
"end",
"api_output",
"end"
]
| Generates a hash that represents the api response based on this
template for the passed model instance. | [
"Generates",
"a",
"hash",
"that",
"represents",
"the",
"api",
"response",
"based",
"on",
"this",
"template",
"for",
"the",
"passed",
"model",
"instance",
"."
]
| 874ccfbcd5efcd90b6b56ec126b07c053675901e | https://github.com/fabrik42/acts_as_api/blob/874ccfbcd5efcd90b6b56ec126b07c053675901e/lib/acts_as_api/api_template.rb#L95-L112 | train |
fabrik42/acts_as_api | lib/acts_as_api/rendering.rb | ActsAsApi.Rendering.render_for_api | def render_for_api(api_template_or_options, render_options)
if api_template_or_options.is_a?(Hash)
api_template = []
api_template << api_template_or_options.delete(:prefix)
api_template << api_template_or_options.delete(:template)
api_template << api_template_or_options.delete(:postfix)
api_template = api_template.reject(&:blank?).join('_')
else
api_template = api_template_or_options
end
# extract the api format and model
api_format_options = {}
ActsAsApi::Config.accepted_api_formats.each do |item|
if render_options.key?(item)
api_format_options[item] = render_options[item]
render_options.delete item
end
end
meta_hash = render_options[:meta] if render_options.key?(:meta)
api_format = api_format_options.keys.first
api_model = api_format_options.values.first
# set the params to render
output_params = render_options
api_root_name = nil
if !output_params[:root].nil?
api_root_name = output_params[:root].to_s
elsif api_model.class.respond_to?(:model_name)
api_root_name = api_model.class.model_name
elsif api_model.respond_to?(:collection_name)
api_root_name = api_model.collection_name
elsif api_model.is_a?(Array) && !api_model.empty? && api_model.first.class.respond_to?(:model_name)
api_root_name = api_model.first.class.model_name
elsif api_model.is_a?(Array) && !api_model.empty? && api_model.first.respond_to?(:model_name)
api_root_name = api_model.first.model_name
elsif api_model.respond_to?(:model_name)
api_root_name = api_model.model_name
else
api_root_name = ActsAsApi::Config.default_root.to_s
end
api_root_name = api_root_name.to_s.underscore.tr('/', '_')
if api_model.is_a?(Array) || (defined?(ActiveRecord) && api_model.is_a?(ActiveRecord::Relation))
api_root_name = api_root_name.pluralize
end
api_root_name = api_root_name.dasherize if ActsAsApi::Config.dasherize_for.include? api_format.to_sym
output_params[:root] = api_root_name
api_response = api_model.as_api_response(api_template)
if api_response.is_a?(Array) && api_format.to_sym == :json && ActsAsApi::Config.include_root_in_json_collections
api_response = api_response.collect { |f| { api_root_name.singularize => f } }
end
if meta_hash || ActsAsApi::Config.add_root_node_for.include?(api_format)
api_response = { api_root_name.to_sym => api_response }
end
api_response = meta_hash.merge api_response if meta_hash
if ActsAsApi::Config.allow_jsonp_callback && params[:callback]
output_params[:callback] = params[:callback]
api_format = :acts_as_api_jsonp if ActsAsApi::Config.add_http_status_to_jsonp_response
end
# create the Hash as response
output_params[api_format] = api_response
render output_params
end | ruby | def render_for_api(api_template_or_options, render_options)
if api_template_or_options.is_a?(Hash)
api_template = []
api_template << api_template_or_options.delete(:prefix)
api_template << api_template_or_options.delete(:template)
api_template << api_template_or_options.delete(:postfix)
api_template = api_template.reject(&:blank?).join('_')
else
api_template = api_template_or_options
end
# extract the api format and model
api_format_options = {}
ActsAsApi::Config.accepted_api_formats.each do |item|
if render_options.key?(item)
api_format_options[item] = render_options[item]
render_options.delete item
end
end
meta_hash = render_options[:meta] if render_options.key?(:meta)
api_format = api_format_options.keys.first
api_model = api_format_options.values.first
# set the params to render
output_params = render_options
api_root_name = nil
if !output_params[:root].nil?
api_root_name = output_params[:root].to_s
elsif api_model.class.respond_to?(:model_name)
api_root_name = api_model.class.model_name
elsif api_model.respond_to?(:collection_name)
api_root_name = api_model.collection_name
elsif api_model.is_a?(Array) && !api_model.empty? && api_model.first.class.respond_to?(:model_name)
api_root_name = api_model.first.class.model_name
elsif api_model.is_a?(Array) && !api_model.empty? && api_model.first.respond_to?(:model_name)
api_root_name = api_model.first.model_name
elsif api_model.respond_to?(:model_name)
api_root_name = api_model.model_name
else
api_root_name = ActsAsApi::Config.default_root.to_s
end
api_root_name = api_root_name.to_s.underscore.tr('/', '_')
if api_model.is_a?(Array) || (defined?(ActiveRecord) && api_model.is_a?(ActiveRecord::Relation))
api_root_name = api_root_name.pluralize
end
api_root_name = api_root_name.dasherize if ActsAsApi::Config.dasherize_for.include? api_format.to_sym
output_params[:root] = api_root_name
api_response = api_model.as_api_response(api_template)
if api_response.is_a?(Array) && api_format.to_sym == :json && ActsAsApi::Config.include_root_in_json_collections
api_response = api_response.collect { |f| { api_root_name.singularize => f } }
end
if meta_hash || ActsAsApi::Config.add_root_node_for.include?(api_format)
api_response = { api_root_name.to_sym => api_response }
end
api_response = meta_hash.merge api_response if meta_hash
if ActsAsApi::Config.allow_jsonp_callback && params[:callback]
output_params[:callback] = params[:callback]
api_format = :acts_as_api_jsonp if ActsAsApi::Config.add_http_status_to_jsonp_response
end
# create the Hash as response
output_params[api_format] = api_response
render output_params
end | [
"def",
"render_for_api",
"(",
"api_template_or_options",
",",
"render_options",
")",
"if",
"api_template_or_options",
".",
"is_a?",
"(",
"Hash",
")",
"api_template",
"=",
"[",
"]",
"api_template",
"<<",
"api_template_or_options",
".",
"delete",
"(",
":prefix",
")",
"api_template",
"<<",
"api_template_or_options",
".",
"delete",
"(",
":template",
")",
"api_template",
"<<",
"api_template_or_options",
".",
"delete",
"(",
":postfix",
")",
"api_template",
"=",
"api_template",
".",
"reject",
"(",
"&",
":blank?",
")",
".",
"join",
"(",
"'_'",
")",
"else",
"api_template",
"=",
"api_template_or_options",
"end",
"api_format_options",
"=",
"{",
"}",
"ActsAsApi",
"::",
"Config",
".",
"accepted_api_formats",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"render_options",
".",
"key?",
"(",
"item",
")",
"api_format_options",
"[",
"item",
"]",
"=",
"render_options",
"[",
"item",
"]",
"render_options",
".",
"delete",
"item",
"end",
"end",
"meta_hash",
"=",
"render_options",
"[",
":meta",
"]",
"if",
"render_options",
".",
"key?",
"(",
":meta",
")",
"api_format",
"=",
"api_format_options",
".",
"keys",
".",
"first",
"api_model",
"=",
"api_format_options",
".",
"values",
".",
"first",
"output_params",
"=",
"render_options",
"api_root_name",
"=",
"nil",
"if",
"!",
"output_params",
"[",
":root",
"]",
".",
"nil?",
"api_root_name",
"=",
"output_params",
"[",
":root",
"]",
".",
"to_s",
"elsif",
"api_model",
".",
"class",
".",
"respond_to?",
"(",
":model_name",
")",
"api_root_name",
"=",
"api_model",
".",
"class",
".",
"model_name",
"elsif",
"api_model",
".",
"respond_to?",
"(",
":collection_name",
")",
"api_root_name",
"=",
"api_model",
".",
"collection_name",
"elsif",
"api_model",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"!",
"api_model",
".",
"empty?",
"&&",
"api_model",
".",
"first",
".",
"class",
".",
"respond_to?",
"(",
":model_name",
")",
"api_root_name",
"=",
"api_model",
".",
"first",
".",
"class",
".",
"model_name",
"elsif",
"api_model",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"!",
"api_model",
".",
"empty?",
"&&",
"api_model",
".",
"first",
".",
"respond_to?",
"(",
":model_name",
")",
"api_root_name",
"=",
"api_model",
".",
"first",
".",
"model_name",
"elsif",
"api_model",
".",
"respond_to?",
"(",
":model_name",
")",
"api_root_name",
"=",
"api_model",
".",
"model_name",
"else",
"api_root_name",
"=",
"ActsAsApi",
"::",
"Config",
".",
"default_root",
".",
"to_s",
"end",
"api_root_name",
"=",
"api_root_name",
".",
"to_s",
".",
"underscore",
".",
"tr",
"(",
"'/'",
",",
"'_'",
")",
"if",
"api_model",
".",
"is_a?",
"(",
"Array",
")",
"||",
"(",
"defined?",
"(",
"ActiveRecord",
")",
"&&",
"api_model",
".",
"is_a?",
"(",
"ActiveRecord",
"::",
"Relation",
")",
")",
"api_root_name",
"=",
"api_root_name",
".",
"pluralize",
"end",
"api_root_name",
"=",
"api_root_name",
".",
"dasherize",
"if",
"ActsAsApi",
"::",
"Config",
".",
"dasherize_for",
".",
"include?",
"api_format",
".",
"to_sym",
"output_params",
"[",
":root",
"]",
"=",
"api_root_name",
"api_response",
"=",
"api_model",
".",
"as_api_response",
"(",
"api_template",
")",
"if",
"api_response",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"api_format",
".",
"to_sym",
"==",
":json",
"&&",
"ActsAsApi",
"::",
"Config",
".",
"include_root_in_json_collections",
"api_response",
"=",
"api_response",
".",
"collect",
"{",
"|",
"f",
"|",
"{",
"api_root_name",
".",
"singularize",
"=>",
"f",
"}",
"}",
"end",
"if",
"meta_hash",
"||",
"ActsAsApi",
"::",
"Config",
".",
"add_root_node_for",
".",
"include?",
"(",
"api_format",
")",
"api_response",
"=",
"{",
"api_root_name",
".",
"to_sym",
"=>",
"api_response",
"}",
"end",
"api_response",
"=",
"meta_hash",
".",
"merge",
"api_response",
"if",
"meta_hash",
"if",
"ActsAsApi",
"::",
"Config",
".",
"allow_jsonp_callback",
"&&",
"params",
"[",
":callback",
"]",
"output_params",
"[",
":callback",
"]",
"=",
"params",
"[",
":callback",
"]",
"api_format",
"=",
":acts_as_api_jsonp",
"if",
"ActsAsApi",
"::",
"Config",
".",
"add_http_status_to_jsonp_response",
"end",
"output_params",
"[",
"api_format",
"]",
"=",
"api_response",
"render",
"output_params",
"end"
]
| Provides an alternative to the +render+ method used within the controller
to simply generate API outputs.
The default Rails serializers are used to serialize the data. | [
"Provides",
"an",
"alternative",
"to",
"the",
"+",
"render",
"+",
"method",
"used",
"within",
"the",
"controller",
"to",
"simply",
"generate",
"API",
"outputs",
"."
]
| 874ccfbcd5efcd90b6b56ec126b07c053675901e | https://github.com/fabrik42/acts_as_api/blob/874ccfbcd5efcd90b6b56ec126b07c053675901e/lib/acts_as_api/rendering.rb#L9-L86 | train |
fabrik42/acts_as_api | lib/acts_as_api/collection.rb | ActsAsApi.Collection.as_api_response | def as_api_response(api_template, options = {})
collect do |item|
if item.respond_to?(:as_api_response)
item.as_api_response(api_template, options)
else
item
end
end
end | ruby | def as_api_response(api_template, options = {})
collect do |item|
if item.respond_to?(:as_api_response)
item.as_api_response(api_template, options)
else
item
end
end
end | [
"def",
"as_api_response",
"(",
"api_template",
",",
"options",
"=",
"{",
"}",
")",
"collect",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"respond_to?",
"(",
":as_api_response",
")",
"item",
".",
"as_api_response",
"(",
"api_template",
",",
"options",
")",
"else",
"item",
"end",
"end",
"end"
]
| The collection checks all its items if they respond to the +as_api_response+ method.
If they do, the result of this method will be collected.
If they don't, the item itself will be collected. | [
"The",
"collection",
"checks",
"all",
"its",
"items",
"if",
"they",
"respond",
"to",
"the",
"+",
"as_api_response",
"+",
"method",
".",
"If",
"they",
"do",
"the",
"result",
"of",
"this",
"method",
"will",
"be",
"collected",
".",
"If",
"they",
"don",
"t",
"the",
"item",
"itself",
"will",
"be",
"collected",
"."
]
| 874ccfbcd5efcd90b6b56ec126b07c053675901e | https://github.com/fabrik42/acts_as_api/blob/874ccfbcd5efcd90b6b56ec126b07c053675901e/lib/acts_as_api/collection.rb#L6-L14 | train |
ccocchi/rabl-rails | lib/rabl-rails/compiler.rb | RablRails.Compiler.condition | def condition(proc)
return unless block_given?
@template.add_node Nodes::Condition.new(proc, sub_compile(nil, true) { yield })
end | ruby | def condition(proc)
return unless block_given?
@template.add_node Nodes::Condition.new(proc, sub_compile(nil, true) { yield })
end | [
"def",
"condition",
"(",
"proc",
")",
"return",
"unless",
"block_given?",
"@template",
".",
"add_node",
"Nodes",
"::",
"Condition",
".",
"new",
"(",
"proc",
",",
"sub_compile",
"(",
"nil",
",",
"true",
")",
"{",
"yield",
"}",
")",
"end"
]
| Provide a conditionnal block
condition(->(u) { u.is_a?(Admin) }) do
attributes :secret
end | [
"Provide",
"a",
"conditionnal",
"block"
]
| 8d4c7eef42b9721e0aa68fece24457368614334f | https://github.com/ccocchi/rabl-rails/blob/8d4c7eef42b9721e0aa68fece24457368614334f/lib/rabl-rails/compiler.rb#L160-L163 | train |
documentcloud/jammit | lib/jammit/command_line.rb | Jammit.CommandLine.ensure_configuration_file | def ensure_configuration_file
config = @options[:config_paths]
return true if File.exists?(config) && File.readable?(config)
puts "Could not find the asset configuration file \"#{config}\""
exit(1)
end | ruby | def ensure_configuration_file
config = @options[:config_paths]
return true if File.exists?(config) && File.readable?(config)
puts "Could not find the asset configuration file \"#{config}\""
exit(1)
end | [
"def",
"ensure_configuration_file",
"config",
"=",
"@options",
"[",
":config_paths",
"]",
"return",
"true",
"if",
"File",
".",
"exists?",
"(",
"config",
")",
"&&",
"File",
".",
"readable?",
"(",
"config",
")",
"puts",
"\"Could not find the asset configuration file \\\"#{config}\\\"\"",
"exit",
"(",
"1",
")",
"end"
]
| Make sure that we have a readable configuration file. The @jammit@
command can't run without one. | [
"Make",
"sure",
"that",
"we",
"have",
"a",
"readable",
"configuration",
"file",
".",
"The"
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/command_line.rb#L37-L42 | train |
documentcloud/jammit | lib/jammit/packager.rb | Jammit.Packager.precache_all | def precache_all(output_dir=nil, base_url=nil)
output_dir ||= File.join(Jammit.public_root, Jammit.package_path)
cacheable(:js, output_dir).each {|p| cache(p, 'js', pack_javascripts(p), output_dir) }
cacheable(:css, output_dir).each do |p|
cache(p, 'css', pack_stylesheets(p), output_dir)
if Jammit.embed_assets
cache(p, 'css', pack_stylesheets(p, :datauri), output_dir, :datauri)
if Jammit.mhtml_enabled
raise MissingConfiguration, "A --base-url option is required in order to generate MHTML." unless base_url
mtime = latest_mtime package_for(p, :css)[:paths]
asset_url = "#{base_url}#{Jammit.asset_url(p, :css, :mhtml, mtime)}"
cache(p, 'css', pack_stylesheets(p, :mhtml, asset_url), output_dir, :mhtml, mtime)
end
end
end
end | ruby | def precache_all(output_dir=nil, base_url=nil)
output_dir ||= File.join(Jammit.public_root, Jammit.package_path)
cacheable(:js, output_dir).each {|p| cache(p, 'js', pack_javascripts(p), output_dir) }
cacheable(:css, output_dir).each do |p|
cache(p, 'css', pack_stylesheets(p), output_dir)
if Jammit.embed_assets
cache(p, 'css', pack_stylesheets(p, :datauri), output_dir, :datauri)
if Jammit.mhtml_enabled
raise MissingConfiguration, "A --base-url option is required in order to generate MHTML." unless base_url
mtime = latest_mtime package_for(p, :css)[:paths]
asset_url = "#{base_url}#{Jammit.asset_url(p, :css, :mhtml, mtime)}"
cache(p, 'css', pack_stylesheets(p, :mhtml, asset_url), output_dir, :mhtml, mtime)
end
end
end
end | [
"def",
"precache_all",
"(",
"output_dir",
"=",
"nil",
",",
"base_url",
"=",
"nil",
")",
"output_dir",
"||=",
"File",
".",
"join",
"(",
"Jammit",
".",
"public_root",
",",
"Jammit",
".",
"package_path",
")",
"cacheable",
"(",
":js",
",",
"output_dir",
")",
".",
"each",
"{",
"|",
"p",
"|",
"cache",
"(",
"p",
",",
"'js'",
",",
"pack_javascripts",
"(",
"p",
")",
",",
"output_dir",
")",
"}",
"cacheable",
"(",
":css",
",",
"output_dir",
")",
".",
"each",
"do",
"|",
"p",
"|",
"cache",
"(",
"p",
",",
"'css'",
",",
"pack_stylesheets",
"(",
"p",
")",
",",
"output_dir",
")",
"if",
"Jammit",
".",
"embed_assets",
"cache",
"(",
"p",
",",
"'css'",
",",
"pack_stylesheets",
"(",
"p",
",",
":datauri",
")",
",",
"output_dir",
",",
":datauri",
")",
"if",
"Jammit",
".",
"mhtml_enabled",
"raise",
"MissingConfiguration",
",",
"\"A --base-url option is required in order to generate MHTML.\"",
"unless",
"base_url",
"mtime",
"=",
"latest_mtime",
"package_for",
"(",
"p",
",",
":css",
")",
"[",
":paths",
"]",
"asset_url",
"=",
"\"#{base_url}#{Jammit.asset_url(p, :css, :mhtml, mtime)}\"",
"cache",
"(",
"p",
",",
"'css'",
",",
"pack_stylesheets",
"(",
"p",
",",
":mhtml",
",",
"asset_url",
")",
",",
"output_dir",
",",
":mhtml",
",",
"mtime",
")",
"end",
"end",
"end",
"end"
]
| Creating a new Packager will rebuild the list of assets from the
Jammit.configuration. When assets.yml is being changed on the fly,
create a new Packager.
Ask the packager to precache all defined assets, along with their gzip'd
versions. In order to prebuild the MHTML stylesheets, we need to know the
base_url, because IE only supports MHTML with absolute references.
Unless forced, will only rebuild assets whose source files have been
changed since their last package build. | [
"Creating",
"a",
"new",
"Packager",
"will",
"rebuild",
"the",
"list",
"of",
"assets",
"from",
"the",
"Jammit",
".",
"configuration",
".",
"When",
"assets",
".",
"yml",
"is",
"being",
"changed",
"on",
"the",
"fly",
"create",
"a",
"new",
"Packager",
".",
"Ask",
"the",
"packager",
"to",
"precache",
"all",
"defined",
"assets",
"along",
"with",
"their",
"gzip",
"d",
"versions",
".",
"In",
"order",
"to",
"prebuild",
"the",
"MHTML",
"stylesheets",
"we",
"need",
"to",
"know",
"the",
"base_url",
"because",
"IE",
"only",
"supports",
"MHTML",
"with",
"absolute",
"references",
".",
"Unless",
"forced",
"will",
"only",
"rebuild",
"assets",
"whose",
"source",
"files",
"have",
"been",
"changed",
"since",
"their",
"last",
"package",
"build",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/packager.rb#L34-L49 | train |
documentcloud/jammit | lib/jammit/packager.rb | Jammit.Packager.cache | def cache(package, extension, contents, output_dir, suffix=nil, mtime=nil)
FileUtils.mkdir_p(output_dir) unless File.exists?(output_dir)
raise OutputNotWritable, "Jammit doesn't have permission to write to \"#{output_dir}\"" unless File.writable?(output_dir)
mtime ||= latest_mtime package_for(package, extension.to_sym)[:paths]
files = []
files << file_name = File.join(output_dir, Jammit.filename(package, extension, suffix))
File.open(file_name, 'wb+') {|f| f.write(contents) }
if Jammit.gzip_assets
files << zip_name = "#{file_name}.gz"
Zlib::GzipWriter.open(zip_name, Zlib::BEST_COMPRESSION) {|f| f.write(contents) }
end
File.utime(mtime, mtime, *files)
end | ruby | def cache(package, extension, contents, output_dir, suffix=nil, mtime=nil)
FileUtils.mkdir_p(output_dir) unless File.exists?(output_dir)
raise OutputNotWritable, "Jammit doesn't have permission to write to \"#{output_dir}\"" unless File.writable?(output_dir)
mtime ||= latest_mtime package_for(package, extension.to_sym)[:paths]
files = []
files << file_name = File.join(output_dir, Jammit.filename(package, extension, suffix))
File.open(file_name, 'wb+') {|f| f.write(contents) }
if Jammit.gzip_assets
files << zip_name = "#{file_name}.gz"
Zlib::GzipWriter.open(zip_name, Zlib::BEST_COMPRESSION) {|f| f.write(contents) }
end
File.utime(mtime, mtime, *files)
end | [
"def",
"cache",
"(",
"package",
",",
"extension",
",",
"contents",
",",
"output_dir",
",",
"suffix",
"=",
"nil",
",",
"mtime",
"=",
"nil",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"output_dir",
")",
"unless",
"File",
".",
"exists?",
"(",
"output_dir",
")",
"raise",
"OutputNotWritable",
",",
"\"Jammit doesn't have permission to write to \\\"#{output_dir}\\\"\"",
"unless",
"File",
".",
"writable?",
"(",
"output_dir",
")",
"mtime",
"||=",
"latest_mtime",
"package_for",
"(",
"package",
",",
"extension",
".",
"to_sym",
")",
"[",
":paths",
"]",
"files",
"=",
"[",
"]",
"files",
"<<",
"file_name",
"=",
"File",
".",
"join",
"(",
"output_dir",
",",
"Jammit",
".",
"filename",
"(",
"package",
",",
"extension",
",",
"suffix",
")",
")",
"File",
".",
"open",
"(",
"file_name",
",",
"'wb+'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"contents",
")",
"}",
"if",
"Jammit",
".",
"gzip_assets",
"files",
"<<",
"zip_name",
"=",
"\"#{file_name}.gz\"",
"Zlib",
"::",
"GzipWriter",
".",
"open",
"(",
"zip_name",
",",
"Zlib",
"::",
"BEST_COMPRESSION",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"contents",
")",
"}",
"end",
"File",
".",
"utime",
"(",
"mtime",
",",
"mtime",
",",
"*",
"files",
")",
"end"
]
| Caches a single prebuilt asset package and gzips it at the highest
compression level. Ensures that the modification time of both both
variants is identical, for web server caching modules, as well as MHTML. | [
"Caches",
"a",
"single",
"prebuilt",
"asset",
"package",
"and",
"gzips",
"it",
"at",
"the",
"highest",
"compression",
"level",
".",
"Ensures",
"that",
"the",
"modification",
"time",
"of",
"both",
"both",
"variants",
"is",
"identical",
"for",
"web",
"server",
"caching",
"modules",
"as",
"well",
"as",
"MHTML",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/packager.rb#L54-L66 | train |
documentcloud/jammit | lib/jammit/packager.rb | Jammit.Packager.pack_stylesheets | def pack_stylesheets(package, variant=nil, asset_url=nil)
compressor.compress_css(package_for(package, :css)[:paths], variant, asset_url)
end | ruby | def pack_stylesheets(package, variant=nil, asset_url=nil)
compressor.compress_css(package_for(package, :css)[:paths], variant, asset_url)
end | [
"def",
"pack_stylesheets",
"(",
"package",
",",
"variant",
"=",
"nil",
",",
"asset_url",
"=",
"nil",
")",
"compressor",
".",
"compress_css",
"(",
"package_for",
"(",
"package",
",",
":css",
")",
"[",
":paths",
"]",
",",
"variant",
",",
"asset_url",
")",
"end"
]
| Return the compressed contents of a stylesheet package. | [
"Return",
"the",
"compressed",
"contents",
"of",
"a",
"stylesheet",
"package",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/packager.rb#L78-L80 | train |
documentcloud/jammit | lib/jammit/packager.rb | Jammit.Packager.package_for | def package_for(package, extension)
pack = @packages[extension] && @packages[extension][package]
pack || not_found(package, extension)
end | ruby | def package_for(package, extension)
pack = @packages[extension] && @packages[extension][package]
pack || not_found(package, extension)
end | [
"def",
"package_for",
"(",
"package",
",",
"extension",
")",
"pack",
"=",
"@packages",
"[",
"extension",
"]",
"&&",
"@packages",
"[",
"extension",
"]",
"[",
"package",
"]",
"pack",
"||",
"not_found",
"(",
"package",
",",
"extension",
")",
"end"
]
| Look up a package asset list by name, raising an exception if the
package has gone missing. | [
"Look",
"up",
"a",
"package",
"asset",
"list",
"by",
"name",
"raising",
"an",
"exception",
"if",
"the",
"package",
"has",
"gone",
"missing",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/packager.rb#L97-L100 | train |
documentcloud/jammit | lib/jammit/controller.rb | Jammit.Controller.package | def package
parse_request
template_ext = Jammit.template_extension.to_sym
case @extension
when :js
render :js => (@contents = Jammit.packager.pack_javascripts(@package))
when template_ext
render :js => (@contents = Jammit.packager.pack_templates(@package))
when :css
render :text => generate_stylesheets, :content_type => 'text/css'
end
cache_package if perform_caching && (@extension != template_ext)
rescue Jammit::PackageNotFound
package_not_found
end | ruby | def package
parse_request
template_ext = Jammit.template_extension.to_sym
case @extension
when :js
render :js => (@contents = Jammit.packager.pack_javascripts(@package))
when template_ext
render :js => (@contents = Jammit.packager.pack_templates(@package))
when :css
render :text => generate_stylesheets, :content_type => 'text/css'
end
cache_package if perform_caching && (@extension != template_ext)
rescue Jammit::PackageNotFound
package_not_found
end | [
"def",
"package",
"parse_request",
"template_ext",
"=",
"Jammit",
".",
"template_extension",
".",
"to_sym",
"case",
"@extension",
"when",
":js",
"render",
":js",
"=>",
"(",
"@contents",
"=",
"Jammit",
".",
"packager",
".",
"pack_javascripts",
"(",
"@package",
")",
")",
"when",
"template_ext",
"render",
":js",
"=>",
"(",
"@contents",
"=",
"Jammit",
".",
"packager",
".",
"pack_templates",
"(",
"@package",
")",
")",
"when",
":css",
"render",
":text",
"=>",
"generate_stylesheets",
",",
":content_type",
"=>",
"'text/css'",
"end",
"cache_package",
"if",
"perform_caching",
"&&",
"(",
"@extension",
"!=",
"template_ext",
")",
"rescue",
"Jammit",
"::",
"PackageNotFound",
"package_not_found",
"end"
]
| The "package" action receives all requests for asset packages that haven't
yet been cached. The package will be built, cached, and gzipped. | [
"The",
"package",
"action",
"receives",
"all",
"requests",
"for",
"asset",
"packages",
"that",
"haven",
"t",
"yet",
"been",
"cached",
".",
"The",
"package",
"will",
"be",
"built",
"cached",
"and",
"gzipped",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/controller.rb#L19-L33 | train |
documentcloud/jammit | lib/jammit/helper.rb | Jammit.Helper.include_stylesheets | def include_stylesheets(*packages)
options = packages.extract_options!
return html_safe(individual_stylesheets(packages, options)) unless should_package?
disabled = (options.delete(:embed_assets) == false) || (options.delete(:embed_images) == false)
return html_safe(packaged_stylesheets(packages, options)) if disabled || !Jammit.embed_assets
return html_safe(embedded_image_stylesheets(packages, options))
end | ruby | def include_stylesheets(*packages)
options = packages.extract_options!
return html_safe(individual_stylesheets(packages, options)) unless should_package?
disabled = (options.delete(:embed_assets) == false) || (options.delete(:embed_images) == false)
return html_safe(packaged_stylesheets(packages, options)) if disabled || !Jammit.embed_assets
return html_safe(embedded_image_stylesheets(packages, options))
end | [
"def",
"include_stylesheets",
"(",
"*",
"packages",
")",
"options",
"=",
"packages",
".",
"extract_options!",
"return",
"html_safe",
"(",
"individual_stylesheets",
"(",
"packages",
",",
"options",
")",
")",
"unless",
"should_package?",
"disabled",
"=",
"(",
"options",
".",
"delete",
"(",
":embed_assets",
")",
"==",
"false",
")",
"||",
"(",
"options",
".",
"delete",
"(",
":embed_images",
")",
"==",
"false",
")",
"return",
"html_safe",
"(",
"packaged_stylesheets",
"(",
"packages",
",",
"options",
")",
")",
"if",
"disabled",
"||",
"!",
"Jammit",
".",
"embed_assets",
"return",
"html_safe",
"(",
"embedded_image_stylesheets",
"(",
"packages",
",",
"options",
")",
")",
"end"
]
| If embed_assets is turned on, writes out links to the Data-URI and MHTML
versions of the stylesheet package, otherwise the package is regular
compressed CSS, and in development the stylesheet URLs are passed verbatim. | [
"If",
"embed_assets",
"is",
"turned",
"on",
"writes",
"out",
"links",
"to",
"the",
"Data",
"-",
"URI",
"and",
"MHTML",
"versions",
"of",
"the",
"stylesheet",
"package",
"otherwise",
"the",
"package",
"is",
"regular",
"compressed",
"CSS",
"and",
"in",
"development",
"the",
"stylesheet",
"URLs",
"are",
"passed",
"verbatim",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/helper.rb#L17-L23 | train |
documentcloud/jammit | lib/jammit/helper.rb | Jammit.Helper.include_javascripts | def include_javascripts(*packages)
options = packages.extract_options!
options.merge!(:extname=>false)
html_safe packages.map {|pack|
should_package? ? Jammit.asset_url(pack, :js) : Jammit.packager.individual_urls(pack.to_sym, :js)
}.flatten.map {|pack|
"<script src=\"#{pack}\"></script>"
}.join("\n")
end | ruby | def include_javascripts(*packages)
options = packages.extract_options!
options.merge!(:extname=>false)
html_safe packages.map {|pack|
should_package? ? Jammit.asset_url(pack, :js) : Jammit.packager.individual_urls(pack.to_sym, :js)
}.flatten.map {|pack|
"<script src=\"#{pack}\"></script>"
}.join("\n")
end | [
"def",
"include_javascripts",
"(",
"*",
"packages",
")",
"options",
"=",
"packages",
".",
"extract_options!",
"options",
".",
"merge!",
"(",
":extname",
"=>",
"false",
")",
"html_safe",
"packages",
".",
"map",
"{",
"|",
"pack",
"|",
"should_package?",
"?",
"Jammit",
".",
"asset_url",
"(",
"pack",
",",
":js",
")",
":",
"Jammit",
".",
"packager",
".",
"individual_urls",
"(",
"pack",
".",
"to_sym",
",",
":js",
")",
"}",
".",
"flatten",
".",
"map",
"{",
"|",
"pack",
"|",
"\"<script src=\\\"#{pack}\\\"></script>\"",
"}",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
]
| Writes out the URL to the bundled and compressed javascript package,
except in development, where it references the individual scripts. | [
"Writes",
"out",
"the",
"URL",
"to",
"the",
"bundled",
"and",
"compressed",
"javascript",
"package",
"except",
"in",
"development",
"where",
"it",
"references",
"the",
"individual",
"scripts",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/helper.rb#L27-L35 | train |
documentcloud/jammit | lib/jammit/helper.rb | Jammit.Helper.individual_stylesheets | def individual_stylesheets(packages, options)
tags_with_options(packages, options) {|p| Jammit.packager.individual_urls(p.to_sym, :css) }
end | ruby | def individual_stylesheets(packages, options)
tags_with_options(packages, options) {|p| Jammit.packager.individual_urls(p.to_sym, :css) }
end | [
"def",
"individual_stylesheets",
"(",
"packages",
",",
"options",
")",
"tags_with_options",
"(",
"packages",
",",
"options",
")",
"{",
"|",
"p",
"|",
"Jammit",
".",
"packager",
".",
"individual_urls",
"(",
"p",
".",
"to_sym",
",",
":css",
")",
"}",
"end"
]
| HTML tags, in order, for all of the individual stylesheets. | [
"HTML",
"tags",
"in",
"order",
"for",
"all",
"of",
"the",
"individual",
"stylesheets",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/helper.rb#L55-L57 | train |
documentcloud/jammit | lib/jammit/helper.rb | Jammit.Helper.packaged_stylesheets | def packaged_stylesheets(packages, options)
tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css) }
end | ruby | def packaged_stylesheets(packages, options)
tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css) }
end | [
"def",
"packaged_stylesheets",
"(",
"packages",
",",
"options",
")",
"tags_with_options",
"(",
"packages",
",",
"options",
")",
"{",
"|",
"p",
"|",
"Jammit",
".",
"asset_url",
"(",
"p",
",",
":css",
")",
"}",
"end"
]
| HTML tags for the stylesheet packages. | [
"HTML",
"tags",
"for",
"the",
"stylesheet",
"packages",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/helper.rb#L60-L62 | train |
documentcloud/jammit | lib/jammit/helper.rb | Jammit.Helper.embedded_image_stylesheets | def embedded_image_stylesheets(packages, options)
datauri_tags = tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css, :datauri) }
ie_tags = Jammit.mhtml_enabled ?
tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css, :mhtml) } :
packaged_stylesheets(packages, options)
[DATA_URI_START, datauri_tags, DATA_URI_END, MHTML_START, ie_tags, MHTML_END].join("\n")
end | ruby | def embedded_image_stylesheets(packages, options)
datauri_tags = tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css, :datauri) }
ie_tags = Jammit.mhtml_enabled ?
tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css, :mhtml) } :
packaged_stylesheets(packages, options)
[DATA_URI_START, datauri_tags, DATA_URI_END, MHTML_START, ie_tags, MHTML_END].join("\n")
end | [
"def",
"embedded_image_stylesheets",
"(",
"packages",
",",
"options",
")",
"datauri_tags",
"=",
"tags_with_options",
"(",
"packages",
",",
"options",
")",
"{",
"|",
"p",
"|",
"Jammit",
".",
"asset_url",
"(",
"p",
",",
":css",
",",
":datauri",
")",
"}",
"ie_tags",
"=",
"Jammit",
".",
"mhtml_enabled",
"?",
"tags_with_options",
"(",
"packages",
",",
"options",
")",
"{",
"|",
"p",
"|",
"Jammit",
".",
"asset_url",
"(",
"p",
",",
":css",
",",
":mhtml",
")",
"}",
":",
"packaged_stylesheets",
"(",
"packages",
",",
"options",
")",
"[",
"DATA_URI_START",
",",
"datauri_tags",
",",
"DATA_URI_END",
",",
"MHTML_START",
",",
"ie_tags",
",",
"MHTML_END",
"]",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
]
| HTML tags for the 'datauri', and 'mhtml' versions of the packaged
stylesheets, using conditional comments to load the correct variant. | [
"HTML",
"tags",
"for",
"the",
"datauri",
"and",
"mhtml",
"versions",
"of",
"the",
"packaged",
"stylesheets",
"using",
"conditional",
"comments",
"to",
"load",
"the",
"correct",
"variant",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/helper.rb#L66-L72 | train |
documentcloud/jammit | lib/jammit/helper.rb | Jammit.Helper.tags_with_options | def tags_with_options(packages, options)
packages.dup.map {|package|
yield package
}.flatten.map {|package|
stylesheet_link_tag package, options
}.join("\n")
end | ruby | def tags_with_options(packages, options)
packages.dup.map {|package|
yield package
}.flatten.map {|package|
stylesheet_link_tag package, options
}.join("\n")
end | [
"def",
"tags_with_options",
"(",
"packages",
",",
"options",
")",
"packages",
".",
"dup",
".",
"map",
"{",
"|",
"package",
"|",
"yield",
"package",
"}",
".",
"flatten",
".",
"map",
"{",
"|",
"package",
"|",
"stylesheet_link_tag",
"package",
",",
"options",
"}",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
]
| Generate the stylesheet tags for a batch of packages, with options, by
yielding each package to a block. | [
"Generate",
"the",
"stylesheet",
"tags",
"for",
"a",
"batch",
"of",
"packages",
"with",
"options",
"by",
"yielding",
"each",
"package",
"to",
"a",
"block",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/helper.rb#L76-L82 | train |
documentcloud/jammit | lib/jammit/compressor.rb | Jammit.Compressor.compile_jst | def compile_jst(paths)
namespace = Jammit.template_namespace
paths = paths.grep(Jammit.template_extension_matcher).sort
base_path = find_base_path(paths)
compiled = paths.map do |path|
contents = read_binary_file(path)
contents = contents.gsub(/\r?\n/, "\\n").gsub("'", '\\\\\'')
name = template_name(path, base_path)
"#{namespace}['#{name}'] = #{Jammit.template_function}('#{contents}');"
end
compiler = Jammit.include_jst_script ? read_binary_file(DEFAULT_JST_SCRIPT) : '';
setup_namespace = "#{namespace} = #{namespace} || {};"
[JST_START, setup_namespace, compiler, compiled, JST_END].flatten.join("\n")
end | ruby | def compile_jst(paths)
namespace = Jammit.template_namespace
paths = paths.grep(Jammit.template_extension_matcher).sort
base_path = find_base_path(paths)
compiled = paths.map do |path|
contents = read_binary_file(path)
contents = contents.gsub(/\r?\n/, "\\n").gsub("'", '\\\\\'')
name = template_name(path, base_path)
"#{namespace}['#{name}'] = #{Jammit.template_function}('#{contents}');"
end
compiler = Jammit.include_jst_script ? read_binary_file(DEFAULT_JST_SCRIPT) : '';
setup_namespace = "#{namespace} = #{namespace} || {};"
[JST_START, setup_namespace, compiler, compiled, JST_END].flatten.join("\n")
end | [
"def",
"compile_jst",
"(",
"paths",
")",
"namespace",
"=",
"Jammit",
".",
"template_namespace",
"paths",
"=",
"paths",
".",
"grep",
"(",
"Jammit",
".",
"template_extension_matcher",
")",
".",
"sort",
"base_path",
"=",
"find_base_path",
"(",
"paths",
")",
"compiled",
"=",
"paths",
".",
"map",
"do",
"|",
"path",
"|",
"contents",
"=",
"read_binary_file",
"(",
"path",
")",
"contents",
"=",
"contents",
".",
"gsub",
"(",
"/",
"\\r",
"\\n",
"/",
",",
"\"\\\\n\"",
")",
".",
"gsub",
"(",
"\"'\"",
",",
"'\\\\\\\\\\''",
")",
"name",
"=",
"template_name",
"(",
"path",
",",
"base_path",
")",
"\"#{namespace}['#{name}'] = #{Jammit.template_function}('#{contents}');\"",
"end",
"compiler",
"=",
"Jammit",
".",
"include_jst_script",
"?",
"read_binary_file",
"(",
"DEFAULT_JST_SCRIPT",
")",
":",
"''",
";",
"setup_namespace",
"=",
"\"#{namespace} = #{namespace} || {};\"",
"[",
"JST_START",
",",
"setup_namespace",
",",
"compiler",
",",
"compiled",
",",
"JST_END",
"]",
".",
"flatten",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
]
| Compiles a single JST file by writing out a javascript that adds
template properties to a top-level template namespace object. Adds a
JST-compilation function to the top of the package, unless you've
specified your own preferred function, or turned it off.
JST templates are named with the basename of their file. | [
"Compiles",
"a",
"single",
"JST",
"file",
"by",
"writing",
"out",
"a",
"javascript",
"that",
"adds",
"template",
"properties",
"to",
"a",
"top",
"-",
"level",
"template",
"namespace",
"object",
".",
"Adds",
"a",
"JST",
"-",
"compilation",
"function",
"to",
"the",
"top",
"of",
"the",
"package",
"unless",
"you",
"ve",
"specified",
"your",
"own",
"preferred",
"function",
"or",
"turned",
"it",
"off",
".",
"JST",
"templates",
"are",
"named",
"with",
"the",
"basename",
"of",
"their",
"file",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/compressor.rb#L110-L123 | train |
documentcloud/jammit | lib/jammit/compressor.rb | Jammit.Compressor.find_base_path | def find_base_path(paths)
return nil if paths.length <= 1
paths.sort!
first = paths.first.split('/')
last = paths.last.split('/')
i = 0
while first[i] == last[i] && i <= first.length
i += 1
end
res = first.slice(0, i).join('/')
res.empty? ? nil : res
end | ruby | def find_base_path(paths)
return nil if paths.length <= 1
paths.sort!
first = paths.first.split('/')
last = paths.last.split('/')
i = 0
while first[i] == last[i] && i <= first.length
i += 1
end
res = first.slice(0, i).join('/')
res.empty? ? nil : res
end | [
"def",
"find_base_path",
"(",
"paths",
")",
"return",
"nil",
"if",
"paths",
".",
"length",
"<=",
"1",
"paths",
".",
"sort!",
"first",
"=",
"paths",
".",
"first",
".",
"split",
"(",
"'/'",
")",
"last",
"=",
"paths",
".",
"last",
".",
"split",
"(",
"'/'",
")",
"i",
"=",
"0",
"while",
"first",
"[",
"i",
"]",
"==",
"last",
"[",
"i",
"]",
"&&",
"i",
"<=",
"first",
".",
"length",
"i",
"+=",
"1",
"end",
"res",
"=",
"first",
".",
"slice",
"(",
"0",
",",
"i",
")",
".",
"join",
"(",
"'/'",
")",
"res",
".",
"empty?",
"?",
"nil",
":",
"res",
"end"
]
| Given a set of paths, find a common prefix path. | [
"Given",
"a",
"set",
"of",
"paths",
"find",
"a",
"common",
"prefix",
"path",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/compressor.rb#L129-L140 | train |
documentcloud/jammit | lib/jammit/compressor.rb | Jammit.Compressor.concatenate_and_tag_assets | def concatenate_and_tag_assets(paths, variant=nil)
stylesheets = [paths].flatten.map do |css_path|
contents = read_binary_file(css_path)
contents.gsub(EMBED_DETECTOR) do |url|
ipath, cpath = Pathname.new($1), Pathname.new(File.expand_path(css_path))
is_url = URI.parse($1).absolute?
is_url ? url : "url(#{construct_asset_path(ipath, cpath, variant)})"
end
end
stylesheets.join("\n")
end | ruby | def concatenate_and_tag_assets(paths, variant=nil)
stylesheets = [paths].flatten.map do |css_path|
contents = read_binary_file(css_path)
contents.gsub(EMBED_DETECTOR) do |url|
ipath, cpath = Pathname.new($1), Pathname.new(File.expand_path(css_path))
is_url = URI.parse($1).absolute?
is_url ? url : "url(#{construct_asset_path(ipath, cpath, variant)})"
end
end
stylesheets.join("\n")
end | [
"def",
"concatenate_and_tag_assets",
"(",
"paths",
",",
"variant",
"=",
"nil",
")",
"stylesheets",
"=",
"[",
"paths",
"]",
".",
"flatten",
".",
"map",
"do",
"|",
"css_path",
"|",
"contents",
"=",
"read_binary_file",
"(",
"css_path",
")",
"contents",
".",
"gsub",
"(",
"EMBED_DETECTOR",
")",
"do",
"|",
"url",
"|",
"ipath",
",",
"cpath",
"=",
"Pathname",
".",
"new",
"(",
"$1",
")",
",",
"Pathname",
".",
"new",
"(",
"File",
".",
"expand_path",
"(",
"css_path",
")",
")",
"is_url",
"=",
"URI",
".",
"parse",
"(",
"$1",
")",
".",
"absolute?",
"is_url",
"?",
"url",
":",
"\"url(#{construct_asset_path(ipath, cpath, variant)})\"",
"end",
"end",
"stylesheets",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
]
| In order to support embedded assets from relative paths, we need to
expand the paths before contatenating the CSS together and losing the
location of the original stylesheet path. Validate the assets while we're
at it. | [
"In",
"order",
"to",
"support",
"embedded",
"assets",
"from",
"relative",
"paths",
"we",
"need",
"to",
"expand",
"the",
"paths",
"before",
"contatenating",
"the",
"CSS",
"together",
"and",
"losing",
"the",
"location",
"of",
"the",
"original",
"stylesheet",
"path",
".",
"Validate",
"the",
"assets",
"while",
"we",
"re",
"at",
"it",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/compressor.rb#L153-L163 | train |
documentcloud/jammit | lib/jammit/compressor.rb | Jammit.Compressor.absolute_path | def absolute_path(asset_pathname, css_pathname)
(asset_pathname.absolute? ?
Pathname.new(File.join(Jammit.public_root, asset_pathname)) :
css_pathname.dirname + asset_pathname).cleanpath
end | ruby | def absolute_path(asset_pathname, css_pathname)
(asset_pathname.absolute? ?
Pathname.new(File.join(Jammit.public_root, asset_pathname)) :
css_pathname.dirname + asset_pathname).cleanpath
end | [
"def",
"absolute_path",
"(",
"asset_pathname",
",",
"css_pathname",
")",
"(",
"asset_pathname",
".",
"absolute?",
"?",
"Pathname",
".",
"new",
"(",
"File",
".",
"join",
"(",
"Jammit",
".",
"public_root",
",",
"asset_pathname",
")",
")",
":",
"css_pathname",
".",
"dirname",
"+",
"asset_pathname",
")",
".",
"cleanpath",
"end"
]
| Get the site-absolute public path for an asset file path that may or may
not be relative, given the path of the stylesheet that contains it. | [
"Get",
"the",
"site",
"-",
"absolute",
"public",
"path",
"for",
"an",
"asset",
"file",
"path",
"that",
"may",
"or",
"may",
"not",
"be",
"relative",
"given",
"the",
"path",
"of",
"the",
"stylesheet",
"that",
"contains",
"it",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/compressor.rb#L201-L205 | train |
documentcloud/jammit | lib/jammit/compressor.rb | Jammit.Compressor.rails_asset_id | def rails_asset_id(path)
asset_id = ENV["RAILS_ASSET_ID"]
return asset_id if asset_id
File.exists?(path) ? File.mtime(path).to_i.to_s : ''
end | ruby | def rails_asset_id(path)
asset_id = ENV["RAILS_ASSET_ID"]
return asset_id if asset_id
File.exists?(path) ? File.mtime(path).to_i.to_s : ''
end | [
"def",
"rails_asset_id",
"(",
"path",
")",
"asset_id",
"=",
"ENV",
"[",
"\"RAILS_ASSET_ID\"",
"]",
"return",
"asset_id",
"if",
"asset_id",
"File",
".",
"exists?",
"(",
"path",
")",
"?",
"File",
".",
"mtime",
"(",
"path",
")",
".",
"to_i",
".",
"to_s",
":",
"''",
"end"
]
| Similar to the AssetTagHelper's method of the same name, this will
determine the correct asset id for a file. | [
"Similar",
"to",
"the",
"AssetTagHelper",
"s",
"method",
"of",
"the",
"same",
"name",
"this",
"will",
"determine",
"the",
"correct",
"asset",
"id",
"for",
"a",
"file",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/compressor.rb#L222-L226 | train |
documentcloud/jammit | lib/jammit/compressor.rb | Jammit.Compressor.embeddable? | def embeddable?(asset_path, variant)
font = EMBED_FONTS.include?(asset_path.extname)
return false unless variant
return false unless asset_path.to_s.match(EMBEDDABLE) && asset_path.exist?
return false unless EMBED_EXTS.include?(asset_path.extname)
return false unless font || encoded_contents(asset_path).length < MAX_IMAGE_SIZE
return false if font && variant == :mhtml
return true
end | ruby | def embeddable?(asset_path, variant)
font = EMBED_FONTS.include?(asset_path.extname)
return false unless variant
return false unless asset_path.to_s.match(EMBEDDABLE) && asset_path.exist?
return false unless EMBED_EXTS.include?(asset_path.extname)
return false unless font || encoded_contents(asset_path).length < MAX_IMAGE_SIZE
return false if font && variant == :mhtml
return true
end | [
"def",
"embeddable?",
"(",
"asset_path",
",",
"variant",
")",
"font",
"=",
"EMBED_FONTS",
".",
"include?",
"(",
"asset_path",
".",
"extname",
")",
"return",
"false",
"unless",
"variant",
"return",
"false",
"unless",
"asset_path",
".",
"to_s",
".",
"match",
"(",
"EMBEDDABLE",
")",
"&&",
"asset_path",
".",
"exist?",
"return",
"false",
"unless",
"EMBED_EXTS",
".",
"include?",
"(",
"asset_path",
".",
"extname",
")",
"return",
"false",
"unless",
"font",
"||",
"encoded_contents",
"(",
"asset_path",
")",
".",
"length",
"<",
"MAX_IMAGE_SIZE",
"return",
"false",
"if",
"font",
"&&",
"variant",
"==",
":mhtml",
"return",
"true",
"end"
]
| An asset is valid for embedding if it exists, is less than 32K, and is
stored somewhere inside of a folder named "embed". IE does not support
Data-URIs larger than 32K, and you probably shouldn't be embedding assets
that large in any case. Because we need to check the base64 length here,
save it so that we don't have to compute it again later. | [
"An",
"asset",
"is",
"valid",
"for",
"embedding",
"if",
"it",
"exists",
"is",
"less",
"than",
"32K",
"and",
"is",
"stored",
"somewhere",
"inside",
"of",
"a",
"folder",
"named",
"embed",
".",
"IE",
"does",
"not",
"support",
"Data",
"-",
"URIs",
"larger",
"than",
"32K",
"and",
"you",
"probably",
"shouldn",
"t",
"be",
"embedding",
"assets",
"that",
"large",
"in",
"any",
"case",
".",
"Because",
"we",
"need",
"to",
"check",
"the",
"base64",
"length",
"here",
"save",
"it",
"so",
"that",
"we",
"don",
"t",
"have",
"to",
"compute",
"it",
"again",
"later",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/compressor.rb#L233-L241 | train |
documentcloud/jammit | lib/jammit/compressor.rb | Jammit.Compressor.encoded_contents | def encoded_contents(asset_path)
return @asset_contents[asset_path] if @asset_contents[asset_path]
data = read_binary_file(asset_path)
@asset_contents[asset_path] = Base64.encode64(data).gsub(/\n/, '')
end | ruby | def encoded_contents(asset_path)
return @asset_contents[asset_path] if @asset_contents[asset_path]
data = read_binary_file(asset_path)
@asset_contents[asset_path] = Base64.encode64(data).gsub(/\n/, '')
end | [
"def",
"encoded_contents",
"(",
"asset_path",
")",
"return",
"@asset_contents",
"[",
"asset_path",
"]",
"if",
"@asset_contents",
"[",
"asset_path",
"]",
"data",
"=",
"read_binary_file",
"(",
"asset_path",
")",
"@asset_contents",
"[",
"asset_path",
"]",
"=",
"Base64",
".",
"encode64",
"(",
"data",
")",
".",
"gsub",
"(",
"/",
"\\n",
"/",
",",
"''",
")",
"end"
]
| Return the Base64-encoded contents of an asset on a single line. | [
"Return",
"the",
"Base64",
"-",
"encoded",
"contents",
"of",
"an",
"asset",
"on",
"a",
"single",
"line",
"."
]
| dc866f1ac3eb069d65215599c451db39d66119a7 | https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/compressor.rb#L244-L248 | train |
progapandist/rubotnik | lib/rubotnik/helpers.rb | Rubotnik.Helpers.say | def say(text, quick_replies: [], user: @user)
message_options = {
recipient: { id: user.id },
message: { text: text }
}
if quick_replies && !quick_replies.empty?
message_options[:message][:quick_replies] = UI::QuickReplies
.build(*quick_replies)
end
send_message(message_options)
end | ruby | def say(text, quick_replies: [], user: @user)
message_options = {
recipient: { id: user.id },
message: { text: text }
}
if quick_replies && !quick_replies.empty?
message_options[:message][:quick_replies] = UI::QuickReplies
.build(*quick_replies)
end
send_message(message_options)
end | [
"def",
"say",
"(",
"text",
",",
"quick_replies",
":",
"[",
"]",
",",
"user",
":",
"@user",
")",
"message_options",
"=",
"{",
"recipient",
":",
"{",
"id",
":",
"user",
".",
"id",
"}",
",",
"message",
":",
"{",
"text",
":",
"text",
"}",
"}",
"if",
"quick_replies",
"&&",
"!",
"quick_replies",
".",
"empty?",
"message_options",
"[",
":message",
"]",
"[",
":quick_replies",
"]",
"=",
"UI",
"::",
"QuickReplies",
".",
"build",
"(",
"*",
"quick_replies",
")",
"end",
"send_message",
"(",
"message_options",
")",
"end"
]
| abstraction over Bot.deliver to send messages declaratively and directly | [
"abstraction",
"over",
"Bot",
".",
"deliver",
"to",
"send",
"messages",
"declaratively",
"and",
"directly"
]
| b79f54b5a3605339281508cb503fa0b6f84f3d07 | https://github.com/progapandist/rubotnik/blob/b79f54b5a3605339281508cb503fa0b6f84f3d07/lib/rubotnik/helpers.rb#L12-L23 | train |
Homebrew/ruby-macho | lib/macho/fat_file.rb | MachO.FatFile.change_dylib_id | def change_dylib_id(new_id, options = {})
raise ArgumentError, "argument must be a String" unless new_id.is_a?(String)
return unless machos.all?(&:dylib?)
each_macho(options) do |macho|
macho.change_dylib_id(new_id, options)
end
repopulate_raw_machos
end | ruby | def change_dylib_id(new_id, options = {})
raise ArgumentError, "argument must be a String" unless new_id.is_a?(String)
return unless machos.all?(&:dylib?)
each_macho(options) do |macho|
macho.change_dylib_id(new_id, options)
end
repopulate_raw_machos
end | [
"def",
"change_dylib_id",
"(",
"new_id",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"argument must be a String\"",
"unless",
"new_id",
".",
"is_a?",
"(",
"String",
")",
"return",
"unless",
"machos",
".",
"all?",
"(",
"&",
":dylib?",
")",
"each_macho",
"(",
"options",
")",
"do",
"|",
"macho",
"|",
"macho",
".",
"change_dylib_id",
"(",
"new_id",
",",
"options",
")",
"end",
"repopulate_raw_machos",
"end"
]
| Changes the file's dylib ID to `new_id`. If the file is not a dylib,
does nothing.
@example
file.change_dylib_id('libFoo.dylib')
@param new_id [String] the new dylib ID
@param options [Hash]
@option options [Boolean] :strict (true) if true, fail if one slice fails.
if false, fail only if all slices fail.
@return [void]
@raise [ArgumentError] if `new_id` is not a String
@see MachOFile#linked_dylibs | [
"Changes",
"the",
"file",
"s",
"dylib",
"ID",
"to",
"new_id",
".",
"If",
"the",
"file",
"is",
"not",
"a",
"dylib",
"does",
"nothing",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/fat_file.rb#L180-L189 | train |
Homebrew/ruby-macho | lib/macho/fat_file.rb | MachO.FatFile.change_install_name | def change_install_name(old_name, new_name, options = {})
each_macho(options) do |macho|
macho.change_install_name(old_name, new_name, options)
end
repopulate_raw_machos
end | ruby | def change_install_name(old_name, new_name, options = {})
each_macho(options) do |macho|
macho.change_install_name(old_name, new_name, options)
end
repopulate_raw_machos
end | [
"def",
"change_install_name",
"(",
"old_name",
",",
"new_name",
",",
"options",
"=",
"{",
"}",
")",
"each_macho",
"(",
"options",
")",
"do",
"|",
"macho",
"|",
"macho",
".",
"change_install_name",
"(",
"old_name",
",",
"new_name",
",",
"options",
")",
"end",
"repopulate_raw_machos",
"end"
]
| Changes all dependent shared library install names from `old_name` to
`new_name`. In a fat file, this changes install names in all internal
Mach-Os.
@example
file.change_install_name('/usr/lib/libFoo.dylib', '/usr/lib/libBar.dylib')
@param old_name [String] the shared library name being changed
@param new_name [String] the new name
@param options [Hash]
@option options [Boolean] :strict (true) if true, fail if one slice fails.
if false, fail only if all slices fail.
@return [void]
@see MachOFile#change_install_name | [
"Changes",
"all",
"dependent",
"shared",
"library",
"install",
"names",
"from",
"old_name",
"to",
"new_name",
".",
"In",
"a",
"fat",
"file",
"this",
"changes",
"install",
"names",
"in",
"all",
"internal",
"Mach",
"-",
"Os",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/fat_file.rb#L215-L221 | train |
Homebrew/ruby-macho | lib/macho/fat_file.rb | MachO.FatFile.change_rpath | def change_rpath(old_path, new_path, options = {})
each_macho(options) do |macho|
macho.change_rpath(old_path, new_path, options)
end
repopulate_raw_machos
end | ruby | def change_rpath(old_path, new_path, options = {})
each_macho(options) do |macho|
macho.change_rpath(old_path, new_path, options)
end
repopulate_raw_machos
end | [
"def",
"change_rpath",
"(",
"old_path",
",",
"new_path",
",",
"options",
"=",
"{",
"}",
")",
"each_macho",
"(",
"options",
")",
"do",
"|",
"macho",
"|",
"macho",
".",
"change_rpath",
"(",
"old_path",
",",
"new_path",
",",
"options",
")",
"end",
"repopulate_raw_machos",
"end"
]
| Change the runtime path `old_path` to `new_path` in the file's Mach-Os.
@param old_path [String] the old runtime path
@param new_path [String] the new runtime path
@param options [Hash]
@option options [Boolean] :strict (true) if true, fail if one slice fails.
if false, fail only if all slices fail.
@return [void]
@see MachOFile#change_rpath | [
"Change",
"the",
"runtime",
"path",
"old_path",
"to",
"new_path",
"in",
"the",
"file",
"s",
"Mach",
"-",
"Os",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/fat_file.rb#L241-L247 | train |
Homebrew/ruby-macho | lib/macho/fat_file.rb | MachO.FatFile.add_rpath | def add_rpath(path, options = {})
each_macho(options) do |macho|
macho.add_rpath(path, options)
end
repopulate_raw_machos
end | ruby | def add_rpath(path, options = {})
each_macho(options) do |macho|
macho.add_rpath(path, options)
end
repopulate_raw_machos
end | [
"def",
"add_rpath",
"(",
"path",
",",
"options",
"=",
"{",
"}",
")",
"each_macho",
"(",
"options",
")",
"do",
"|",
"macho",
"|",
"macho",
".",
"add_rpath",
"(",
"path",
",",
"options",
")",
"end",
"repopulate_raw_machos",
"end"
]
| Add the given runtime path to the file's Mach-Os.
@param path [String] the new runtime path
@param options [Hash]
@option options [Boolean] :strict (true) if true, fail if one slice fails.
if false, fail only if all slices fail.
@return [void]
@see MachOFile#add_rpath | [
"Add",
"the",
"given",
"runtime",
"path",
"to",
"the",
"file",
"s",
"Mach",
"-",
"Os",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/fat_file.rb#L256-L262 | train |
Homebrew/ruby-macho | lib/macho/fat_file.rb | MachO.FatFile.delete_rpath | def delete_rpath(path, options = {})
each_macho(options) do |macho|
macho.delete_rpath(path, options)
end
repopulate_raw_machos
end | ruby | def delete_rpath(path, options = {})
each_macho(options) do |macho|
macho.delete_rpath(path, options)
end
repopulate_raw_machos
end | [
"def",
"delete_rpath",
"(",
"path",
",",
"options",
"=",
"{",
"}",
")",
"each_macho",
"(",
"options",
")",
"do",
"|",
"macho",
"|",
"macho",
".",
"delete_rpath",
"(",
"path",
",",
"options",
")",
"end",
"repopulate_raw_machos",
"end"
]
| Delete the given runtime path from the file's Mach-Os.
@param path [String] the runtime path to delete
@param options [Hash]
@option options [Boolean] :strict (true) if true, fail if one slice fails.
if false, fail only if all slices fail.
@return void
@see MachOFile#delete_rpath | [
"Delete",
"the",
"given",
"runtime",
"path",
"from",
"the",
"file",
"s",
"Mach",
"-",
"Os",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/fat_file.rb#L271-L277 | train |
Homebrew/ruby-macho | lib/macho/fat_file.rb | MachO.FatFile.populate_fat_header | def populate_fat_header
# the smallest fat Mach-O header is 8 bytes
raise TruncatedFileError if @raw_data.size < 8
fh = Headers::FatHeader.new_from_bin(:big, @raw_data[0, Headers::FatHeader.bytesize])
raise MagicError, fh.magic unless Utils.magic?(fh.magic)
raise MachOBinaryError unless Utils.fat_magic?(fh.magic)
# Rationale: Java classfiles have the same magic as big-endian fat
# Mach-Os. Classfiles encode their version at the same offset as
# `nfat_arch` and the lowest version number is 43, so we error out
# if a file claims to have over 30 internal architectures. It's
# technically possible for a fat Mach-O to have over 30 architectures,
# but this is extremely unlikely and in practice distinguishes the two
# formats.
raise JavaClassFileError if fh.nfat_arch > 30
fh
end | ruby | def populate_fat_header
# the smallest fat Mach-O header is 8 bytes
raise TruncatedFileError if @raw_data.size < 8
fh = Headers::FatHeader.new_from_bin(:big, @raw_data[0, Headers::FatHeader.bytesize])
raise MagicError, fh.magic unless Utils.magic?(fh.magic)
raise MachOBinaryError unless Utils.fat_magic?(fh.magic)
# Rationale: Java classfiles have the same magic as big-endian fat
# Mach-Os. Classfiles encode their version at the same offset as
# `nfat_arch` and the lowest version number is 43, so we error out
# if a file claims to have over 30 internal architectures. It's
# technically possible for a fat Mach-O to have over 30 architectures,
# but this is extremely unlikely and in practice distinguishes the two
# formats.
raise JavaClassFileError if fh.nfat_arch > 30
fh
end | [
"def",
"populate_fat_header",
"raise",
"TruncatedFileError",
"if",
"@raw_data",
".",
"size",
"<",
"8",
"fh",
"=",
"Headers",
"::",
"FatHeader",
".",
"new_from_bin",
"(",
":big",
",",
"@raw_data",
"[",
"0",
",",
"Headers",
"::",
"FatHeader",
".",
"bytesize",
"]",
")",
"raise",
"MagicError",
",",
"fh",
".",
"magic",
"unless",
"Utils",
".",
"magic?",
"(",
"fh",
".",
"magic",
")",
"raise",
"MachOBinaryError",
"unless",
"Utils",
".",
"fat_magic?",
"(",
"fh",
".",
"magic",
")",
"raise",
"JavaClassFileError",
"if",
"fh",
".",
"nfat_arch",
">",
"30",
"fh",
"end"
]
| Obtain the fat header from raw file data.
@return [Headers::FatHeader] the fat header
@raise [TruncatedFileError] if the file is too small to have a
valid header
@raise [MagicError] if the magic is not valid Mach-O magic
@raise [MachOBinaryError] if the magic is for a non-fat Mach-O file
@raise [JavaClassFileError] if the file is a Java classfile
@api private | [
"Obtain",
"the",
"fat",
"header",
"from",
"raw",
"file",
"data",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/fat_file.rb#L324-L343 | train |
Homebrew/ruby-macho | lib/macho/fat_file.rb | MachO.FatFile.populate_fat_archs | def populate_fat_archs
archs = []
fa_klass = Utils.fat_magic32?(header.magic) ? Headers::FatArch : Headers::FatArch64
fa_off = Headers::FatHeader.bytesize
fa_len = fa_klass.bytesize
header.nfat_arch.times do |i|
archs << fa_klass.new_from_bin(:big, @raw_data[fa_off + (fa_len * i), fa_len])
end
archs
end | ruby | def populate_fat_archs
archs = []
fa_klass = Utils.fat_magic32?(header.magic) ? Headers::FatArch : Headers::FatArch64
fa_off = Headers::FatHeader.bytesize
fa_len = fa_klass.bytesize
header.nfat_arch.times do |i|
archs << fa_klass.new_from_bin(:big, @raw_data[fa_off + (fa_len * i), fa_len])
end
archs
end | [
"def",
"populate_fat_archs",
"archs",
"=",
"[",
"]",
"fa_klass",
"=",
"Utils",
".",
"fat_magic32?",
"(",
"header",
".",
"magic",
")",
"?",
"Headers",
"::",
"FatArch",
":",
"Headers",
"::",
"FatArch64",
"fa_off",
"=",
"Headers",
"::",
"FatHeader",
".",
"bytesize",
"fa_len",
"=",
"fa_klass",
".",
"bytesize",
"header",
".",
"nfat_arch",
".",
"times",
"do",
"|",
"i",
"|",
"archs",
"<<",
"fa_klass",
".",
"new_from_bin",
"(",
":big",
",",
"@raw_data",
"[",
"fa_off",
"+",
"(",
"fa_len",
"*",
"i",
")",
",",
"fa_len",
"]",
")",
"end",
"archs",
"end"
]
| Obtain an array of fat architectures from raw file data.
@return [Array<Headers::FatArch>] an array of fat architectures
@api private | [
"Obtain",
"an",
"array",
"of",
"fat",
"architectures",
"from",
"raw",
"file",
"data",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/fat_file.rb#L348-L360 | train |
Homebrew/ruby-macho | lib/macho/fat_file.rb | MachO.FatFile.populate_machos | def populate_machos
machos = []
fat_archs.each do |arch|
machos << MachOFile.new_from_bin(@raw_data[arch.offset, arch.size], **options)
end
machos
end | ruby | def populate_machos
machos = []
fat_archs.each do |arch|
machos << MachOFile.new_from_bin(@raw_data[arch.offset, arch.size], **options)
end
machos
end | [
"def",
"populate_machos",
"machos",
"=",
"[",
"]",
"fat_archs",
".",
"each",
"do",
"|",
"arch",
"|",
"machos",
"<<",
"MachOFile",
".",
"new_from_bin",
"(",
"@raw_data",
"[",
"arch",
".",
"offset",
",",
"arch",
".",
"size",
"]",
",",
"**",
"options",
")",
"end",
"machos",
"end"
]
| Obtain an array of Mach-O blobs from raw file data.
@return [Array<MachOFile>] an array of Mach-Os
@api private | [
"Obtain",
"an",
"array",
"of",
"Mach",
"-",
"O",
"blobs",
"from",
"raw",
"file",
"data",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/fat_file.rb#L365-L373 | train |
Homebrew/ruby-macho | lib/macho/fat_file.rb | MachO.FatFile.repopulate_raw_machos | def repopulate_raw_machos
machos.each_with_index do |macho, i|
arch = fat_archs[i]
@raw_data[arch.offset, arch.size] = macho.serialize
end
end | ruby | def repopulate_raw_machos
machos.each_with_index do |macho, i|
arch = fat_archs[i]
@raw_data[arch.offset, arch.size] = macho.serialize
end
end | [
"def",
"repopulate_raw_machos",
"machos",
".",
"each_with_index",
"do",
"|",
"macho",
",",
"i",
"|",
"arch",
"=",
"fat_archs",
"[",
"i",
"]",
"@raw_data",
"[",
"arch",
".",
"offset",
",",
"arch",
".",
"size",
"]",
"=",
"macho",
".",
"serialize",
"end",
"end"
]
| Repopulate the raw Mach-O data with each internal Mach-O object.
@return [void]
@api private | [
"Repopulate",
"the",
"raw",
"Mach",
"-",
"O",
"data",
"with",
"each",
"internal",
"Mach",
"-",
"O",
"object",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/fat_file.rb#L378-L384 | train |
Homebrew/ruby-macho | lib/macho/fat_file.rb | MachO.FatFile.each_macho | def each_macho(options = {})
strict = options.fetch(:strict, true)
errors = []
machos.each_with_index do |macho, index|
begin
yield macho
rescue RecoverableModificationError => e
e.macho_slice = index
# Strict mode: Immediately re-raise. Otherwise: Retain, check later.
raise e if strict
errors << e
end
end
# Non-strict mode: Raise first error if *all* Mach-O slices failed.
raise errors.first if errors.size == machos.size
end | ruby | def each_macho(options = {})
strict = options.fetch(:strict, true)
errors = []
machos.each_with_index do |macho, index|
begin
yield macho
rescue RecoverableModificationError => e
e.macho_slice = index
# Strict mode: Immediately re-raise. Otherwise: Retain, check later.
raise e if strict
errors << e
end
end
# Non-strict mode: Raise first error if *all* Mach-O slices failed.
raise errors.first if errors.size == machos.size
end | [
"def",
"each_macho",
"(",
"options",
"=",
"{",
"}",
")",
"strict",
"=",
"options",
".",
"fetch",
"(",
":strict",
",",
"true",
")",
"errors",
"=",
"[",
"]",
"machos",
".",
"each_with_index",
"do",
"|",
"macho",
",",
"index",
"|",
"begin",
"yield",
"macho",
"rescue",
"RecoverableModificationError",
"=>",
"e",
"e",
".",
"macho_slice",
"=",
"index",
"raise",
"e",
"if",
"strict",
"errors",
"<<",
"e",
"end",
"end",
"raise",
"errors",
".",
"first",
"if",
"errors",
".",
"size",
"==",
"machos",
".",
"size",
"end"
]
| Yield each Mach-O object in the file, rescuing and accumulating errors.
@param options [Hash]
@option options [Boolean] :strict (true) whether or not to fail loudly
with an exception if at least one Mach-O raises an exception. If false,
only raises an exception if *all* Mach-Os raise exceptions.
@raise [RecoverableModificationError] under the conditions of
the `:strict` option above.
@api private | [
"Yield",
"each",
"Mach",
"-",
"O",
"object",
"in",
"the",
"file",
"rescuing",
"and",
"accumulating",
"errors",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/fat_file.rb#L394-L413 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.insert_command | def insert_command(offset, lc, options = {})
context = LoadCommands::LoadCommand::SerializationContext.context_for(self)
cmd_raw = lc.serialize(context)
fileoff = offset + cmd_raw.bytesize
raise OffsetInsertionError, offset if offset < header.class.bytesize || fileoff > low_fileoff
new_sizeofcmds = sizeofcmds + cmd_raw.bytesize
raise HeaderPadError, @filename if header.class.bytesize + new_sizeofcmds > low_fileoff
# update Mach-O header fields to account for inserted load command
update_ncmds(ncmds + 1)
update_sizeofcmds(new_sizeofcmds)
@raw_data.insert(offset, cmd_raw)
@raw_data.slice!(header.class.bytesize + new_sizeofcmds, cmd_raw.bytesize)
populate_fields if options.fetch(:repopulate, true)
end | ruby | def insert_command(offset, lc, options = {})
context = LoadCommands::LoadCommand::SerializationContext.context_for(self)
cmd_raw = lc.serialize(context)
fileoff = offset + cmd_raw.bytesize
raise OffsetInsertionError, offset if offset < header.class.bytesize || fileoff > low_fileoff
new_sizeofcmds = sizeofcmds + cmd_raw.bytesize
raise HeaderPadError, @filename if header.class.bytesize + new_sizeofcmds > low_fileoff
# update Mach-O header fields to account for inserted load command
update_ncmds(ncmds + 1)
update_sizeofcmds(new_sizeofcmds)
@raw_data.insert(offset, cmd_raw)
@raw_data.slice!(header.class.bytesize + new_sizeofcmds, cmd_raw.bytesize)
populate_fields if options.fetch(:repopulate, true)
end | [
"def",
"insert_command",
"(",
"offset",
",",
"lc",
",",
"options",
"=",
"{",
"}",
")",
"context",
"=",
"LoadCommands",
"::",
"LoadCommand",
"::",
"SerializationContext",
".",
"context_for",
"(",
"self",
")",
"cmd_raw",
"=",
"lc",
".",
"serialize",
"(",
"context",
")",
"fileoff",
"=",
"offset",
"+",
"cmd_raw",
".",
"bytesize",
"raise",
"OffsetInsertionError",
",",
"offset",
"if",
"offset",
"<",
"header",
".",
"class",
".",
"bytesize",
"||",
"fileoff",
">",
"low_fileoff",
"new_sizeofcmds",
"=",
"sizeofcmds",
"+",
"cmd_raw",
".",
"bytesize",
"raise",
"HeaderPadError",
",",
"@filename",
"if",
"header",
".",
"class",
".",
"bytesize",
"+",
"new_sizeofcmds",
">",
"low_fileoff",
"update_ncmds",
"(",
"ncmds",
"+",
"1",
")",
"update_sizeofcmds",
"(",
"new_sizeofcmds",
")",
"@raw_data",
".",
"insert",
"(",
"offset",
",",
"cmd_raw",
")",
"@raw_data",
".",
"slice!",
"(",
"header",
".",
"class",
".",
"bytesize",
"+",
"new_sizeofcmds",
",",
"cmd_raw",
".",
"bytesize",
")",
"populate_fields",
"if",
"options",
".",
"fetch",
"(",
":repopulate",
",",
"true",
")",
"end"
]
| Inserts a load command at the given offset.
@param offset [Integer] the offset to insert at
@param lc [LoadCommands::LoadCommand] the load command to insert
@param options [Hash]
@option options [Boolean] :repopulate (true) whether or not to repopulate
the instance fields
@raise [OffsetInsertionError] if the offset is not in the load command region
@raise [HeaderPadError] if the new command exceeds the header pad buffer
@note Calling this method with an arbitrary offset in the load command
region **will leave the object in an inconsistent state**. | [
"Inserts",
"a",
"load",
"command",
"at",
"the",
"given",
"offset",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L155-L174 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.replace_command | def replace_command(old_lc, new_lc)
context = LoadCommands::LoadCommand::SerializationContext.context_for(self)
cmd_raw = new_lc.serialize(context)
new_sizeofcmds = sizeofcmds + cmd_raw.bytesize - old_lc.cmdsize
raise HeaderPadError, @filename if header.class.bytesize + new_sizeofcmds > low_fileoff
delete_command(old_lc)
insert_command(old_lc.view.offset, new_lc)
end | ruby | def replace_command(old_lc, new_lc)
context = LoadCommands::LoadCommand::SerializationContext.context_for(self)
cmd_raw = new_lc.serialize(context)
new_sizeofcmds = sizeofcmds + cmd_raw.bytesize - old_lc.cmdsize
raise HeaderPadError, @filename if header.class.bytesize + new_sizeofcmds > low_fileoff
delete_command(old_lc)
insert_command(old_lc.view.offset, new_lc)
end | [
"def",
"replace_command",
"(",
"old_lc",
",",
"new_lc",
")",
"context",
"=",
"LoadCommands",
"::",
"LoadCommand",
"::",
"SerializationContext",
".",
"context_for",
"(",
"self",
")",
"cmd_raw",
"=",
"new_lc",
".",
"serialize",
"(",
"context",
")",
"new_sizeofcmds",
"=",
"sizeofcmds",
"+",
"cmd_raw",
".",
"bytesize",
"-",
"old_lc",
".",
"cmdsize",
"raise",
"HeaderPadError",
",",
"@filename",
"if",
"header",
".",
"class",
".",
"bytesize",
"+",
"new_sizeofcmds",
">",
"low_fileoff",
"delete_command",
"(",
"old_lc",
")",
"insert_command",
"(",
"old_lc",
".",
"view",
".",
"offset",
",",
"new_lc",
")",
"end"
]
| Replace a load command with another command in the Mach-O, preserving location.
@param old_lc [LoadCommands::LoadCommand] the load command being replaced
@param new_lc [LoadCommands::LoadCommand] the load command being added
@return [void]
@raise [HeaderPadError] if the new command exceeds the header pad buffer
@see #insert_command
@note This is public, but methods like {#dylib_id=} should be preferred. | [
"Replace",
"a",
"load",
"command",
"with",
"another",
"command",
"in",
"the",
"Mach",
"-",
"O",
"preserving",
"location",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L183-L192 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.delete_command | def delete_command(lc, options = {})
@raw_data.slice!(lc.view.offset, lc.cmdsize)
# update Mach-O header fields to account for deleted load command
update_ncmds(ncmds - 1)
update_sizeofcmds(sizeofcmds - lc.cmdsize)
# pad the space after the load commands to preserve offsets
@raw_data.insert(header.class.bytesize + sizeofcmds - lc.cmdsize, Utils.nullpad(lc.cmdsize))
populate_fields if options.fetch(:repopulate, true)
end | ruby | def delete_command(lc, options = {})
@raw_data.slice!(lc.view.offset, lc.cmdsize)
# update Mach-O header fields to account for deleted load command
update_ncmds(ncmds - 1)
update_sizeofcmds(sizeofcmds - lc.cmdsize)
# pad the space after the load commands to preserve offsets
@raw_data.insert(header.class.bytesize + sizeofcmds - lc.cmdsize, Utils.nullpad(lc.cmdsize))
populate_fields if options.fetch(:repopulate, true)
end | [
"def",
"delete_command",
"(",
"lc",
",",
"options",
"=",
"{",
"}",
")",
"@raw_data",
".",
"slice!",
"(",
"lc",
".",
"view",
".",
"offset",
",",
"lc",
".",
"cmdsize",
")",
"update_ncmds",
"(",
"ncmds",
"-",
"1",
")",
"update_sizeofcmds",
"(",
"sizeofcmds",
"-",
"lc",
".",
"cmdsize",
")",
"@raw_data",
".",
"insert",
"(",
"header",
".",
"class",
".",
"bytesize",
"+",
"sizeofcmds",
"-",
"lc",
".",
"cmdsize",
",",
"Utils",
".",
"nullpad",
"(",
"lc",
".",
"cmdsize",
")",
")",
"populate_fields",
"if",
"options",
".",
"fetch",
"(",
":repopulate",
",",
"true",
")",
"end"
]
| Delete a load command from the Mach-O.
@param lc [LoadCommands::LoadCommand] the load command being deleted
@param options [Hash]
@option options [Boolean] :repopulate (true) whether or not to repopulate
the instance fields
@return [void]
@note This is public, but methods like {#delete_rpath} should be preferred.
Setting `repopulate` to false **will leave the instance in an
inconsistent state** unless {#populate_fields} is called **immediately**
afterwards. | [
"Delete",
"a",
"load",
"command",
"from",
"the",
"Mach",
"-",
"O",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L219-L230 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.segment_alignment | def segment_alignment
# special cases: 12 for x86/64/PPC/PP64, 14 for ARM/ARM64
return 12 if %i[i386 x86_64 ppc ppc64].include?(cputype)
return 14 if %i[arm arm64].include?(cputype)
cur_align = Sections::MAX_SECT_ALIGN
segments.each do |segment|
if filetype == :object
# start with the smallest alignment, and work our way up
align = magic32? ? 2 : 3
segment.sections.each do |section|
align = section.align unless section.align <= align
end
else
align = segment.guess_align
end
cur_align = align if align < cur_align
end
cur_align
end | ruby | def segment_alignment
# special cases: 12 for x86/64/PPC/PP64, 14 for ARM/ARM64
return 12 if %i[i386 x86_64 ppc ppc64].include?(cputype)
return 14 if %i[arm arm64].include?(cputype)
cur_align = Sections::MAX_SECT_ALIGN
segments.each do |segment|
if filetype == :object
# start with the smallest alignment, and work our way up
align = magic32? ? 2 : 3
segment.sections.each do |section|
align = section.align unless section.align <= align
end
else
align = segment.guess_align
end
cur_align = align if align < cur_align
end
cur_align
end | [
"def",
"segment_alignment",
"return",
"12",
"if",
"%i[",
"i386",
"x86_64",
"ppc",
"ppc64",
"]",
".",
"include?",
"(",
"cputype",
")",
"return",
"14",
"if",
"%i[",
"arm",
"arm64",
"]",
".",
"include?",
"(",
"cputype",
")",
"cur_align",
"=",
"Sections",
"::",
"MAX_SECT_ALIGN",
"segments",
".",
"each",
"do",
"|",
"segment",
"|",
"if",
"filetype",
"==",
":object",
"align",
"=",
"magic32?",
"?",
"2",
":",
"3",
"segment",
".",
"sections",
".",
"each",
"do",
"|",
"section",
"|",
"align",
"=",
"section",
".",
"align",
"unless",
"section",
".",
"align",
"<=",
"align",
"end",
"else",
"align",
"=",
"segment",
".",
"guess_align",
"end",
"cur_align",
"=",
"align",
"if",
"align",
"<",
"cur_align",
"end",
"cur_align",
"end"
]
| The segment alignment for the Mach-O. Guesses conservatively.
@return [Integer] the alignment, as a power of 2
@note This is **not** the same as {#alignment}!
@note See `get_align` and `get_align_64` in `cctools/misc/lipo.c` | [
"The",
"segment",
"alignment",
"for",
"the",
"Mach",
"-",
"O",
".",
"Guesses",
"conservatively",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L263-L284 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.change_dylib_id | def change_dylib_id(new_id, _options = {})
raise ArgumentError, "new ID must be a String" unless new_id.is_a?(String)
return unless dylib?
old_lc = command(:LC_ID_DYLIB).first
raise DylibIdMissingError unless old_lc
new_lc = LoadCommands::LoadCommand.create(:LC_ID_DYLIB, new_id,
old_lc.timestamp,
old_lc.current_version,
old_lc.compatibility_version)
replace_command(old_lc, new_lc)
end | ruby | def change_dylib_id(new_id, _options = {})
raise ArgumentError, "new ID must be a String" unless new_id.is_a?(String)
return unless dylib?
old_lc = command(:LC_ID_DYLIB).first
raise DylibIdMissingError unless old_lc
new_lc = LoadCommands::LoadCommand.create(:LC_ID_DYLIB, new_id,
old_lc.timestamp,
old_lc.current_version,
old_lc.compatibility_version)
replace_command(old_lc, new_lc)
end | [
"def",
"change_dylib_id",
"(",
"new_id",
",",
"_options",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"new ID must be a String\"",
"unless",
"new_id",
".",
"is_a?",
"(",
"String",
")",
"return",
"unless",
"dylib?",
"old_lc",
"=",
"command",
"(",
":LC_ID_DYLIB",
")",
".",
"first",
"raise",
"DylibIdMissingError",
"unless",
"old_lc",
"new_lc",
"=",
"LoadCommands",
"::",
"LoadCommand",
".",
"create",
"(",
":LC_ID_DYLIB",
",",
"new_id",
",",
"old_lc",
".",
"timestamp",
",",
"old_lc",
".",
"current_version",
",",
"old_lc",
".",
"compatibility_version",
")",
"replace_command",
"(",
"old_lc",
",",
"new_lc",
")",
"end"
]
| Changes the Mach-O's dylib ID to `new_id`. Does nothing if not a dylib.
@example
file.change_dylib_id("libFoo.dylib")
@param new_id [String] the dylib's new ID
@param _options [Hash]
@return [void]
@raise [ArgumentError] if `new_id` is not a String
@note `_options` is currently unused and is provided for signature
compatibility with {MachO::FatFile#change_dylib_id} | [
"Changes",
"the",
"Mach",
"-",
"O",
"s",
"dylib",
"ID",
"to",
"new_id",
".",
"Does",
"nothing",
"if",
"not",
"a",
"dylib",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L307-L320 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.change_install_name | def change_install_name(old_name, new_name, _options = {})
old_lc = dylib_load_commands.find { |d| d.name.to_s == old_name }
raise DylibUnknownError, old_name if old_lc.nil?
new_lc = LoadCommands::LoadCommand.create(old_lc.type, new_name,
old_lc.timestamp,
old_lc.current_version,
old_lc.compatibility_version)
replace_command(old_lc, new_lc)
end | ruby | def change_install_name(old_name, new_name, _options = {})
old_lc = dylib_load_commands.find { |d| d.name.to_s == old_name }
raise DylibUnknownError, old_name if old_lc.nil?
new_lc = LoadCommands::LoadCommand.create(old_lc.type, new_name,
old_lc.timestamp,
old_lc.current_version,
old_lc.compatibility_version)
replace_command(old_lc, new_lc)
end | [
"def",
"change_install_name",
"(",
"old_name",
",",
"new_name",
",",
"_options",
"=",
"{",
"}",
")",
"old_lc",
"=",
"dylib_load_commands",
".",
"find",
"{",
"|",
"d",
"|",
"d",
".",
"name",
".",
"to_s",
"==",
"old_name",
"}",
"raise",
"DylibUnknownError",
",",
"old_name",
"if",
"old_lc",
".",
"nil?",
"new_lc",
"=",
"LoadCommands",
"::",
"LoadCommand",
".",
"create",
"(",
"old_lc",
".",
"type",
",",
"new_name",
",",
"old_lc",
".",
"timestamp",
",",
"old_lc",
".",
"current_version",
",",
"old_lc",
".",
"compatibility_version",
")",
"replace_command",
"(",
"old_lc",
",",
"new_lc",
")",
"end"
]
| Changes the shared library `old_name` to `new_name`
@example
file.change_install_name("abc.dylib", "def.dylib")
@param old_name [String] the shared library's old name
@param new_name [String] the shared library's new name
@param _options [Hash]
@return [void]
@raise [DylibUnknownError] if no shared library has the old name
@note `_options` is currently unused and is provided for signature
compatibility with {MachO::FatFile#change_install_name} | [
"Changes",
"the",
"shared",
"library",
"old_name",
"to",
"new_name"
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L344-L354 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.change_rpath | def change_rpath(old_path, new_path, _options = {})
old_lc = command(:LC_RPATH).find { |r| r.path.to_s == old_path }
raise RpathUnknownError, old_path if old_lc.nil?
raise RpathExistsError, new_path if rpaths.include?(new_path)
new_lc = LoadCommands::LoadCommand.create(:LC_RPATH, new_path)
delete_rpath(old_path)
insert_command(old_lc.view.offset, new_lc)
end | ruby | def change_rpath(old_path, new_path, _options = {})
old_lc = command(:LC_RPATH).find { |r| r.path.to_s == old_path }
raise RpathUnknownError, old_path if old_lc.nil?
raise RpathExistsError, new_path if rpaths.include?(new_path)
new_lc = LoadCommands::LoadCommand.create(:LC_RPATH, new_path)
delete_rpath(old_path)
insert_command(old_lc.view.offset, new_lc)
end | [
"def",
"change_rpath",
"(",
"old_path",
",",
"new_path",
",",
"_options",
"=",
"{",
"}",
")",
"old_lc",
"=",
"command",
"(",
":LC_RPATH",
")",
".",
"find",
"{",
"|",
"r",
"|",
"r",
".",
"path",
".",
"to_s",
"==",
"old_path",
"}",
"raise",
"RpathUnknownError",
",",
"old_path",
"if",
"old_lc",
".",
"nil?",
"raise",
"RpathExistsError",
",",
"new_path",
"if",
"rpaths",
".",
"include?",
"(",
"new_path",
")",
"new_lc",
"=",
"LoadCommands",
"::",
"LoadCommand",
".",
"create",
"(",
":LC_RPATH",
",",
"new_path",
")",
"delete_rpath",
"(",
"old_path",
")",
"insert_command",
"(",
"old_lc",
".",
"view",
".",
"offset",
",",
"new_lc",
")",
"end"
]
| Changes the runtime path `old_path` to `new_path`
@example
file.change_rpath("/usr/lib", "/usr/local/lib")
@param old_path [String] the old runtime path
@param new_path [String] the new runtime path
@param _options [Hash]
@return [void]
@raise [RpathUnknownError] if no such old runtime path exists
@raise [RpathExistsError] if the new runtime path already exists
@note `_options` is currently unused and is provided for signature
compatibility with {MachO::FatFile#change_rpath} | [
"Changes",
"the",
"runtime",
"path",
"old_path",
"to",
"new_path"
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L375-L384 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.add_rpath | def add_rpath(path, _options = {})
raise RpathExistsError, path if rpaths.include?(path)
rpath_cmd = LoadCommands::LoadCommand.create(:LC_RPATH, path)
add_command(rpath_cmd)
end | ruby | def add_rpath(path, _options = {})
raise RpathExistsError, path if rpaths.include?(path)
rpath_cmd = LoadCommands::LoadCommand.create(:LC_RPATH, path)
add_command(rpath_cmd)
end | [
"def",
"add_rpath",
"(",
"path",
",",
"_options",
"=",
"{",
"}",
")",
"raise",
"RpathExistsError",
",",
"path",
"if",
"rpaths",
".",
"include?",
"(",
"path",
")",
"rpath_cmd",
"=",
"LoadCommands",
"::",
"LoadCommand",
".",
"create",
"(",
":LC_RPATH",
",",
"path",
")",
"add_command",
"(",
"rpath_cmd",
")",
"end"
]
| Add the given runtime path to the Mach-O.
@example
file.rpaths # => ["/lib"]
file.add_rpath("/usr/lib")
file.rpaths # => ["/lib", "/usr/lib"]
@param path [String] the new runtime path
@param _options [Hash]
@return [void]
@raise [RpathExistsError] if the runtime path already exists
@note `_options` is currently unused and is provided for signature
compatibility with {MachO::FatFile#add_rpath} | [
"Add",
"the",
"given",
"runtime",
"path",
"to",
"the",
"Mach",
"-",
"O",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L397-L402 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.delete_rpath | def delete_rpath(path, _options = {})
rpath_cmds = command(:LC_RPATH).select { |r| r.path.to_s == path }
raise RpathUnknownError, path if rpath_cmds.empty?
# delete the commands in reverse order, offset descending. this
# allows us to defer (expensive) field population until the very end
rpath_cmds.reverse_each { |cmd| delete_command(cmd, :repopulate => false) }
populate_fields
end | ruby | def delete_rpath(path, _options = {})
rpath_cmds = command(:LC_RPATH).select { |r| r.path.to_s == path }
raise RpathUnknownError, path if rpath_cmds.empty?
# delete the commands in reverse order, offset descending. this
# allows us to defer (expensive) field population until the very end
rpath_cmds.reverse_each { |cmd| delete_command(cmd, :repopulate => false) }
populate_fields
end | [
"def",
"delete_rpath",
"(",
"path",
",",
"_options",
"=",
"{",
"}",
")",
"rpath_cmds",
"=",
"command",
"(",
":LC_RPATH",
")",
".",
"select",
"{",
"|",
"r",
"|",
"r",
".",
"path",
".",
"to_s",
"==",
"path",
"}",
"raise",
"RpathUnknownError",
",",
"path",
"if",
"rpath_cmds",
".",
"empty?",
"rpath_cmds",
".",
"reverse_each",
"{",
"|",
"cmd",
"|",
"delete_command",
"(",
"cmd",
",",
":repopulate",
"=>",
"false",
")",
"}",
"populate_fields",
"end"
]
| Delete the given runtime path from the Mach-O.
@example
file.rpaths # => ["/lib"]
file.delete_rpath("/lib")
file.rpaths # => []
@param path [String] the runtime path to delete
@param _options [Hash]
@return void
@raise [RpathUnknownError] if no such runtime path exists
@note `_options` is currently unused and is provided for signature
compatibility with {MachO::FatFile#delete_rpath} | [
"Delete",
"the",
"given",
"runtime",
"path",
"from",
"the",
"Mach",
"-",
"O",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L415-L424 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.populate_mach_header | def populate_mach_header
# the smallest Mach-O header is 28 bytes
raise TruncatedFileError if @raw_data.size < 28
magic = populate_and_check_magic
mh_klass = Utils.magic32?(magic) ? Headers::MachHeader : Headers::MachHeader64
mh = mh_klass.new_from_bin(endianness, @raw_data[0, mh_klass.bytesize])
check_cputype(mh.cputype)
check_cpusubtype(mh.cputype, mh.cpusubtype)
check_filetype(mh.filetype)
mh
end | ruby | def populate_mach_header
# the smallest Mach-O header is 28 bytes
raise TruncatedFileError if @raw_data.size < 28
magic = populate_and_check_magic
mh_klass = Utils.magic32?(magic) ? Headers::MachHeader : Headers::MachHeader64
mh = mh_klass.new_from_bin(endianness, @raw_data[0, mh_klass.bytesize])
check_cputype(mh.cputype)
check_cpusubtype(mh.cputype, mh.cpusubtype)
check_filetype(mh.filetype)
mh
end | [
"def",
"populate_mach_header",
"raise",
"TruncatedFileError",
"if",
"@raw_data",
".",
"size",
"<",
"28",
"magic",
"=",
"populate_and_check_magic",
"mh_klass",
"=",
"Utils",
".",
"magic32?",
"(",
"magic",
")",
"?",
"Headers",
"::",
"MachHeader",
":",
"Headers",
"::",
"MachHeader64",
"mh",
"=",
"mh_klass",
".",
"new_from_bin",
"(",
"endianness",
",",
"@raw_data",
"[",
"0",
",",
"mh_klass",
".",
"bytesize",
"]",
")",
"check_cputype",
"(",
"mh",
".",
"cputype",
")",
"check_cpusubtype",
"(",
"mh",
".",
"cputype",
",",
"mh",
".",
"cpusubtype",
")",
"check_filetype",
"(",
"mh",
".",
"filetype",
")",
"mh",
"end"
]
| The file's Mach-O header structure.
@return [Headers::MachHeader] if the Mach-O is 32-bit
@return [Headers::MachHeader64] if the Mach-O is 64-bit
@raise [TruncatedFileError] if the file is too small to have a valid header
@api private | [
"The",
"file",
"s",
"Mach",
"-",
"O",
"header",
"structure",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L458-L471 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.populate_and_check_magic | def populate_and_check_magic
magic = @raw_data[0..3].unpack("N").first
raise MagicError, magic unless Utils.magic?(magic)
raise FatBinaryError if Utils.fat_magic?(magic)
@endianness = Utils.little_magic?(magic) ? :little : :big
magic
end | ruby | def populate_and_check_magic
magic = @raw_data[0..3].unpack("N").first
raise MagicError, magic unless Utils.magic?(magic)
raise FatBinaryError if Utils.fat_magic?(magic)
@endianness = Utils.little_magic?(magic) ? :little : :big
magic
end | [
"def",
"populate_and_check_magic",
"magic",
"=",
"@raw_data",
"[",
"0",
"..",
"3",
"]",
".",
"unpack",
"(",
"\"N\"",
")",
".",
"first",
"raise",
"MagicError",
",",
"magic",
"unless",
"Utils",
".",
"magic?",
"(",
"magic",
")",
"raise",
"FatBinaryError",
"if",
"Utils",
".",
"fat_magic?",
"(",
"magic",
")",
"@endianness",
"=",
"Utils",
".",
"little_magic?",
"(",
"magic",
")",
"?",
":little",
":",
":big",
"magic",
"end"
]
| Read just the file's magic number and check its validity.
@return [Integer] the magic
@raise [MagicError] if the magic is not valid Mach-O magic
@raise [FatBinaryError] if the magic is for a Fat file
@api private | [
"Read",
"just",
"the",
"file",
"s",
"magic",
"number",
"and",
"check",
"its",
"validity",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L478-L487 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.populate_load_commands | def populate_load_commands
permissive = options.fetch(:permissive, false)
offset = header.class.bytesize
load_commands = []
header.ncmds.times do
fmt = Utils.specialize_format("L=", endianness)
cmd = @raw_data.slice(offset, 4).unpack(fmt).first
cmd_sym = LoadCommands::LOAD_COMMANDS[cmd]
raise LoadCommandError, cmd unless cmd_sym || permissive
# If we're here, then either cmd_sym represents a valid load
# command *or* we're in permissive mode.
klass = if (klass_str = LoadCommands::LC_STRUCTURES[cmd_sym])
LoadCommands.const_get klass_str
else
LoadCommands::LoadCommand
end
view = MachOView.new(@raw_data, endianness, offset)
command = klass.new_from_bin(view)
load_commands << command
offset += command.cmdsize
end
load_commands
end | ruby | def populate_load_commands
permissive = options.fetch(:permissive, false)
offset = header.class.bytesize
load_commands = []
header.ncmds.times do
fmt = Utils.specialize_format("L=", endianness)
cmd = @raw_data.slice(offset, 4).unpack(fmt).first
cmd_sym = LoadCommands::LOAD_COMMANDS[cmd]
raise LoadCommandError, cmd unless cmd_sym || permissive
# If we're here, then either cmd_sym represents a valid load
# command *or* we're in permissive mode.
klass = if (klass_str = LoadCommands::LC_STRUCTURES[cmd_sym])
LoadCommands.const_get klass_str
else
LoadCommands::LoadCommand
end
view = MachOView.new(@raw_data, endianness, offset)
command = klass.new_from_bin(view)
load_commands << command
offset += command.cmdsize
end
load_commands
end | [
"def",
"populate_load_commands",
"permissive",
"=",
"options",
".",
"fetch",
"(",
":permissive",
",",
"false",
")",
"offset",
"=",
"header",
".",
"class",
".",
"bytesize",
"load_commands",
"=",
"[",
"]",
"header",
".",
"ncmds",
".",
"times",
"do",
"fmt",
"=",
"Utils",
".",
"specialize_format",
"(",
"\"L=\"",
",",
"endianness",
")",
"cmd",
"=",
"@raw_data",
".",
"slice",
"(",
"offset",
",",
"4",
")",
".",
"unpack",
"(",
"fmt",
")",
".",
"first",
"cmd_sym",
"=",
"LoadCommands",
"::",
"LOAD_COMMANDS",
"[",
"cmd",
"]",
"raise",
"LoadCommandError",
",",
"cmd",
"unless",
"cmd_sym",
"||",
"permissive",
"klass",
"=",
"if",
"(",
"klass_str",
"=",
"LoadCommands",
"::",
"LC_STRUCTURES",
"[",
"cmd_sym",
"]",
")",
"LoadCommands",
".",
"const_get",
"klass_str",
"else",
"LoadCommands",
"::",
"LoadCommand",
"end",
"view",
"=",
"MachOView",
".",
"new",
"(",
"@raw_data",
",",
"endianness",
",",
"offset",
")",
"command",
"=",
"klass",
".",
"new_from_bin",
"(",
"view",
")",
"load_commands",
"<<",
"command",
"offset",
"+=",
"command",
".",
"cmdsize",
"end",
"load_commands",
"end"
]
| All load commands in the file.
@return [Array<LoadCommands::LoadCommand>] an array of load commands
@raise [LoadCommandError] if an unknown load command is encountered
@api private | [
"All",
"load",
"commands",
"in",
"the",
"file",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L518-L546 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.update_ncmds | def update_ncmds(ncmds)
fmt = Utils.specialize_format("L=", endianness)
ncmds_raw = [ncmds].pack(fmt)
@raw_data[16..19] = ncmds_raw
end | ruby | def update_ncmds(ncmds)
fmt = Utils.specialize_format("L=", endianness)
ncmds_raw = [ncmds].pack(fmt)
@raw_data[16..19] = ncmds_raw
end | [
"def",
"update_ncmds",
"(",
"ncmds",
")",
"fmt",
"=",
"Utils",
".",
"specialize_format",
"(",
"\"L=\"",
",",
"endianness",
")",
"ncmds_raw",
"=",
"[",
"ncmds",
"]",
".",
"pack",
"(",
"fmt",
")",
"@raw_data",
"[",
"16",
"..",
"19",
"]",
"=",
"ncmds_raw",
"end"
]
| Updates the number of load commands in the raw data.
@param ncmds [Integer] the new number of commands
@return [void]
@api private | [
"Updates",
"the",
"number",
"of",
"load",
"commands",
"in",
"the",
"raw",
"data",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L572-L576 | train |
Homebrew/ruby-macho | lib/macho/macho_file.rb | MachO.MachOFile.update_sizeofcmds | def update_sizeofcmds(size)
fmt = Utils.specialize_format("L=", endianness)
size_raw = [size].pack(fmt)
@raw_data[20..23] = size_raw
end | ruby | def update_sizeofcmds(size)
fmt = Utils.specialize_format("L=", endianness)
size_raw = [size].pack(fmt)
@raw_data[20..23] = size_raw
end | [
"def",
"update_sizeofcmds",
"(",
"size",
")",
"fmt",
"=",
"Utils",
".",
"specialize_format",
"(",
"\"L=\"",
",",
"endianness",
")",
"size_raw",
"=",
"[",
"size",
"]",
".",
"pack",
"(",
"fmt",
")",
"@raw_data",
"[",
"20",
"..",
"23",
"]",
"=",
"size_raw",
"end"
]
| Updates the size of all load commands in the raw data.
@param size [Integer] the new size, in bytes
@return [void]
@api private | [
"Updates",
"the",
"size",
"of",
"all",
"load",
"commands",
"in",
"the",
"raw",
"data",
"."
]
| a1dedc25bc78a9bd6366988d12e122ee3d420e8c | https://github.com/Homebrew/ruby-macho/blob/a1dedc25bc78a9bd6366988d12e122ee3d420e8c/lib/macho/macho_file.rb#L582-L586 | train |
makaroni4/sandi_meter | lib/sandi_meter/analyzer.rb | SandiMeter.Analyzer.number_of_arguments | def number_of_arguments(method_sexp)
arguments = method_sexp[2]
arguments = arguments[1] if arguments.first == :paren
arguments[1] == nil ? 0 : arguments[1].size
end | ruby | def number_of_arguments(method_sexp)
arguments = method_sexp[2]
arguments = arguments[1] if arguments.first == :paren
arguments[1] == nil ? 0 : arguments[1].size
end | [
"def",
"number_of_arguments",
"(",
"method_sexp",
")",
"arguments",
"=",
"method_sexp",
"[",
"2",
"]",
"arguments",
"=",
"arguments",
"[",
"1",
"]",
"if",
"arguments",
".",
"first",
"==",
":paren",
"arguments",
"[",
"1",
"]",
"==",
"nil",
"?",
"0",
":",
"arguments",
"[",
"1",
"]",
".",
"size",
"end"
]
| MOVE
to method scanner class | [
"MOVE",
"to",
"method",
"scanner",
"class"
]
| a8d04630cc196edf748ae8cdd66b9c53f0878de0 | https://github.com/makaroni4/sandi_meter/blob/a8d04630cc196edf748ae8cdd66b9c53f0878de0/lib/sandi_meter/analyzer.rb#L67-L72 | train |
dnsimple/dnsimple-ruby | lib/dnsimple/client.rb | Dnsimple.Client.execute | def execute(method, path, data = nil, options = {})
response = request(method, path, data, options)
case response.code
when 200..299
response
when 401
raise AuthenticationFailed, response["message"]
when 404
raise NotFoundError, response
else
raise RequestError, response
end
end | ruby | def execute(method, path, data = nil, options = {})
response = request(method, path, data, options)
case response.code
when 200..299
response
when 401
raise AuthenticationFailed, response["message"]
when 404
raise NotFoundError, response
else
raise RequestError, response
end
end | [
"def",
"execute",
"(",
"method",
",",
"path",
",",
"data",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"request",
"(",
"method",
",",
"path",
",",
"data",
",",
"options",
")",
"case",
"response",
".",
"code",
"when",
"200",
"..",
"299",
"response",
"when",
"401",
"raise",
"AuthenticationFailed",
",",
"response",
"[",
"\"message\"",
"]",
"when",
"404",
"raise",
"NotFoundError",
",",
"response",
"else",
"raise",
"RequestError",
",",
"response",
"end",
"end"
]
| Executes a request, validates and returns the response.
@param [String] method The HTTP method
@param [String] path The path, relative to {#base_url}
@param [Hash] data The body for the request
@param [Hash] options The query and header params for the request
@return [HTTParty::Response]
@raise [RequestError]
@raise [NotFoundError]
@raise [AuthenticationFailed]
@raise [TwoFactorAuthenticationRequired] | [
"Executes",
"a",
"request",
"validates",
"and",
"returns",
"the",
"response",
"."
]
| cb75e47ec4de89954e56a80498796269717beb23 | https://github.com/dnsimple/dnsimple-ruby/blob/cb75e47ec4de89954e56a80498796269717beb23/lib/dnsimple/client.rb#L154-L167 | train |
dnsimple/dnsimple-ruby | lib/dnsimple/client.rb | Dnsimple.Client.request | def request(method, path, data = nil, options = {})
request_options = request_options(options)
if data
request_options[:headers]["Content-Type"] = content_type(request_options[:headers])
request_options[:body] = content_data(request_options[:headers], data)
end
HTTParty.send(method, base_url + path, request_options)
end | ruby | def request(method, path, data = nil, options = {})
request_options = request_options(options)
if data
request_options[:headers]["Content-Type"] = content_type(request_options[:headers])
request_options[:body] = content_data(request_options[:headers], data)
end
HTTParty.send(method, base_url + path, request_options)
end | [
"def",
"request",
"(",
"method",
",",
"path",
",",
"data",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"request_options",
"=",
"request_options",
"(",
"options",
")",
"if",
"data",
"request_options",
"[",
":headers",
"]",
"[",
"\"Content-Type\"",
"]",
"=",
"content_type",
"(",
"request_options",
"[",
":headers",
"]",
")",
"request_options",
"[",
":body",
"]",
"=",
"content_data",
"(",
"request_options",
"[",
":headers",
"]",
",",
"data",
")",
"end",
"HTTParty",
".",
"send",
"(",
"method",
",",
"base_url",
"+",
"path",
",",
"request_options",
")",
"end"
]
| Make a HTTP request.
This method doesn't validate the response and never raise errors
even in case of HTTP error codes, except for connection errors raised by
the underlying HTTP client.
Therefore, it's up to the caller to properly handle and validate the response.
@param [String] method The HTTP method
@param [String] path The path, relative to {#base_url}
@param [Hash] data The body for the request
@param [Hash] options The query and header params for the request
@return [HTTParty::Response] | [
"Make",
"a",
"HTTP",
"request",
"."
]
| cb75e47ec4de89954e56a80498796269717beb23 | https://github.com/dnsimple/dnsimple-ruby/blob/cb75e47ec4de89954e56a80498796269717beb23/lib/dnsimple/client.rb#L182-L191 | train |
jpmobile/jpmobile | lib/jpmobile/request_with_mobile.rb | Jpmobile.RequestWithMobile.remote_addr | def remote_addr
if respond_to?(:remote_ip)
__send__(:remote_ip) # for Rails
elsif respond_to?(:ip)
__send__(:ip) # for Rack
else
if env['HTTP_X_FORWARDED_FOR']
env['HTTP_X_FORWARDED_FOR'].split(',').pop
else
env['REMOTE_ADDR']
end
end
end | ruby | def remote_addr
if respond_to?(:remote_ip)
__send__(:remote_ip) # for Rails
elsif respond_to?(:ip)
__send__(:ip) # for Rack
else
if env['HTTP_X_FORWARDED_FOR']
env['HTTP_X_FORWARDED_FOR'].split(',').pop
else
env['REMOTE_ADDR']
end
end
end | [
"def",
"remote_addr",
"if",
"respond_to?",
"(",
":remote_ip",
")",
"__send__",
"(",
":remote_ip",
")",
"elsif",
"respond_to?",
"(",
":ip",
")",
"__send__",
"(",
":ip",
")",
"else",
"if",
"env",
"[",
"'HTTP_X_FORWARDED_FOR'",
"]",
"env",
"[",
"'HTTP_X_FORWARDED_FOR'",
"]",
".",
"split",
"(",
"','",
")",
".",
"pop",
"else",
"env",
"[",
"'REMOTE_ADDR'",
"]",
"end",
"end",
"end"
]
| for reverse proxy. | [
"for",
"reverse",
"proxy",
"."
]
| 4758f4a3fafbd8dc8c6051f3b79b231e4742612b | https://github.com/jpmobile/jpmobile/blob/4758f4a3fafbd8dc8c6051f3b79b231e4742612b/lib/jpmobile/request_with_mobile.rb#L13-L25 | train |
jpmobile/jpmobile | lib/jpmobile/mobile/abstract_mobile.rb | Jpmobile::Mobile.AbstractMobile.variants | def variants
return @_variants if @_variants
@_variants = self.class.ancestors.select {|c| c.to_s =~ /^Jpmobile/ && c.to_s !~ /Emoticon/ }.map do |klass|
klass = klass.to_s.
gsub(/Jpmobile::/, '').
gsub(/AbstractMobile::/, '').
gsub(/Mobile::SmartPhone/, 'smart_phone').
gsub(/Mobile::Tablet/, 'tablet').
gsub(/::/, '_').
gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').
gsub(/([a-z\d])([A-Z])/, '\1_\2').
downcase
(klass =~ /abstract/) ? 'mobile' : klass
end
if @_variants.include?('tablet')
@_variants = @_variants.reject {|v| v == 'mobile' }.map {|v| v.gsub(/mobile_/, 'tablet_') }
elsif @_variants.include?('smart_phone')
@_variants = @_variants.reject {|v| v == 'mobile' }.map {|v| v.gsub(/mobile_/, 'smart_phone_') }
end
@_variants || []
end | ruby | def variants
return @_variants if @_variants
@_variants = self.class.ancestors.select {|c| c.to_s =~ /^Jpmobile/ && c.to_s !~ /Emoticon/ }.map do |klass|
klass = klass.to_s.
gsub(/Jpmobile::/, '').
gsub(/AbstractMobile::/, '').
gsub(/Mobile::SmartPhone/, 'smart_phone').
gsub(/Mobile::Tablet/, 'tablet').
gsub(/::/, '_').
gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').
gsub(/([a-z\d])([A-Z])/, '\1_\2').
downcase
(klass =~ /abstract/) ? 'mobile' : klass
end
if @_variants.include?('tablet')
@_variants = @_variants.reject {|v| v == 'mobile' }.map {|v| v.gsub(/mobile_/, 'tablet_') }
elsif @_variants.include?('smart_phone')
@_variants = @_variants.reject {|v| v == 'mobile' }.map {|v| v.gsub(/mobile_/, 'smart_phone_') }
end
@_variants || []
end | [
"def",
"variants",
"return",
"@_variants",
"if",
"@_variants",
"@_variants",
"=",
"self",
".",
"class",
".",
"ancestors",
".",
"select",
"{",
"|",
"c",
"|",
"c",
".",
"to_s",
"=~",
"/",
"/",
"&&",
"c",
".",
"to_s",
"!~",
"/",
"/",
"}",
".",
"map",
"do",
"|",
"klass",
"|",
"klass",
"=",
"klass",
".",
"to_s",
".",
"gsub",
"(",
"/",
"/",
",",
"''",
")",
".",
"gsub",
"(",
"/",
"/",
",",
"''",
")",
".",
"gsub",
"(",
"/",
"/",
",",
"'smart_phone'",
")",
".",
"gsub",
"(",
"/",
"/",
",",
"'tablet'",
")",
".",
"gsub",
"(",
"/",
"/",
",",
"'_'",
")",
".",
"gsub",
"(",
"/",
"/",
",",
"'\\1_\\2'",
")",
".",
"gsub",
"(",
"/",
"\\d",
"/",
",",
"'\\1_\\2'",
")",
".",
"downcase",
"(",
"klass",
"=~",
"/",
"/",
")",
"?",
"'mobile'",
":",
"klass",
"end",
"if",
"@_variants",
".",
"include?",
"(",
"'tablet'",
")",
"@_variants",
"=",
"@_variants",
".",
"reject",
"{",
"|",
"v",
"|",
"v",
"==",
"'mobile'",
"}",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"gsub",
"(",
"/",
"/",
",",
"'tablet_'",
")",
"}",
"elsif",
"@_variants",
".",
"include?",
"(",
"'smart_phone'",
")",
"@_variants",
"=",
"@_variants",
".",
"reject",
"{",
"|",
"v",
"|",
"v",
"==",
"'mobile'",
"}",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"gsub",
"(",
"/",
"/",
",",
"'smart_phone_'",
")",
"}",
"end",
"@_variants",
"||",
"[",
"]",
"end"
]
| for view selector | [
"for",
"view",
"selector"
]
| 4758f4a3fafbd8dc8c6051f3b79b231e4742612b | https://github.com/jpmobile/jpmobile/blob/4758f4a3fafbd8dc8c6051f3b79b231e4742612b/lib/jpmobile/mobile/abstract_mobile.rb#L94-L117 | train |
code-mancers/rapidfire | app/models/rapidfire/question.rb | Rapidfire.Question.validate_answer | def validate_answer(answer)
if rules[:presence] == "1"
answer.validates_presence_of :answer_text
end
if rules[:minimum].present? || rules[:maximum].present?
min_max = { minimum: rules[:minimum].to_i }
min_max[:maximum] = rules[:maximum].to_i if rules[:maximum].present?
answer.validates_length_of :answer_text, min_max
end
end | ruby | def validate_answer(answer)
if rules[:presence] == "1"
answer.validates_presence_of :answer_text
end
if rules[:minimum].present? || rules[:maximum].present?
min_max = { minimum: rules[:minimum].to_i }
min_max[:maximum] = rules[:maximum].to_i if rules[:maximum].present?
answer.validates_length_of :answer_text, min_max
end
end | [
"def",
"validate_answer",
"(",
"answer",
")",
"if",
"rules",
"[",
":presence",
"]",
"==",
"\"1\"",
"answer",
".",
"validates_presence_of",
":answer_text",
"end",
"if",
"rules",
"[",
":minimum",
"]",
".",
"present?",
"||",
"rules",
"[",
":maximum",
"]",
".",
"present?",
"min_max",
"=",
"{",
"minimum",
":",
"rules",
"[",
":minimum",
"]",
".",
"to_i",
"}",
"min_max",
"[",
":maximum",
"]",
"=",
"rules",
"[",
":maximum",
"]",
".",
"to_i",
"if",
"rules",
"[",
":maximum",
"]",
".",
"present?",
"answer",
".",
"validates_length_of",
":answer_text",
",",
"min_max",
"end",
"end"
]
| answer will delegate its validation to question, and question
will inturn add validations on answer on the fly! | [
"answer",
"will",
"delegate",
"its",
"validation",
"to",
"question",
"and",
"question",
"will",
"inturn",
"add",
"validations",
"on",
"answer",
"on",
"the",
"fly!"
]
| f536c489bd2a8a5195c19275f7dce6d3e980524d | https://github.com/code-mancers/rapidfire/blob/f536c489bd2a8a5195c19275f7dce6d3e980524d/app/models/rapidfire/question.rb#L31-L42 | train |
tdiary/tdiary-core | misc/plugin/category-legacy.rb | Category.Cache.replace_sections | def replace_sections(diary)
return if diary.nil? or !diary.categorizable?
categorized = categorize_diary(diary)
categories = restore_categories
deleted = []
ymd = diary.date.strftime('%Y%m%d')
@plugin.__send__(:transaction, 'category') do |db|
categories.each do |c|
cat = get(db, c) || {}
if diary.visible? and categorized[c]
cat.update(categorized[c])
set(db, c, cat)
else
# diary is invisible or sections of this category is deleted
cat.delete(ymd)
if cat.empty?
db.delete(c)
deleted << c
else
set(db, c, cat)
end
end
end
if !deleted.empty?
replace_categories(categories - deleted)
end
end
end | ruby | def replace_sections(diary)
return if diary.nil? or !diary.categorizable?
categorized = categorize_diary(diary)
categories = restore_categories
deleted = []
ymd = diary.date.strftime('%Y%m%d')
@plugin.__send__(:transaction, 'category') do |db|
categories.each do |c|
cat = get(db, c) || {}
if diary.visible? and categorized[c]
cat.update(categorized[c])
set(db, c, cat)
else
# diary is invisible or sections of this category is deleted
cat.delete(ymd)
if cat.empty?
db.delete(c)
deleted << c
else
set(db, c, cat)
end
end
end
if !deleted.empty?
replace_categories(categories - deleted)
end
end
end | [
"def",
"replace_sections",
"(",
"diary",
")",
"return",
"if",
"diary",
".",
"nil?",
"or",
"!",
"diary",
".",
"categorizable?",
"categorized",
"=",
"categorize_diary",
"(",
"diary",
")",
"categories",
"=",
"restore_categories",
"deleted",
"=",
"[",
"]",
"ymd",
"=",
"diary",
".",
"date",
".",
"strftime",
"(",
"'%Y%m%d'",
")",
"@plugin",
".",
"__send__",
"(",
":transaction",
",",
"'category'",
")",
"do",
"|",
"db",
"|",
"categories",
".",
"each",
"do",
"|",
"c",
"|",
"cat",
"=",
"get",
"(",
"db",
",",
"c",
")",
"||",
"{",
"}",
"if",
"diary",
".",
"visible?",
"and",
"categorized",
"[",
"c",
"]",
"cat",
".",
"update",
"(",
"categorized",
"[",
"c",
"]",
")",
"set",
"(",
"db",
",",
"c",
",",
"cat",
")",
"else",
"cat",
".",
"delete",
"(",
"ymd",
")",
"if",
"cat",
".",
"empty?",
"db",
".",
"delete",
"(",
"c",
")",
"deleted",
"<<",
"c",
"else",
"set",
"(",
"db",
",",
"c",
",",
"cat",
")",
"end",
"end",
"end",
"if",
"!",
"deleted",
".",
"empty?",
"replace_categories",
"(",
"categories",
"-",
"deleted",
")",
"end",
"end",
"end"
]
| cache each section of diary
used in update_proc | [
"cache",
"each",
"section",
"of",
"diary",
"used",
"in",
"update_proc"
]
| 688b9378a872d6530ebd51788355fcd56b0f5b2d | https://github.com/tdiary/tdiary-core/blob/688b9378a872d6530ebd51788355fcd56b0f5b2d/misc/plugin/category-legacy.rb#L435-L465 | train |
tdiary/tdiary-core | misc/plugin/category-legacy.rb | Category.Cache.categorize | def categorize(category, years)
categories = category - ['ALL']
if categories.empty?
categories = restore_categories
else
categories &= restore_categories
end
categorized = {}
begin
categorized.clear
categories.each do |c|
@plugin.__send__(:transaction, 'category') do |db|
categorized[c] = get(db, c)
end
categorized[c].keys.each do |ymd|
y, m = ymd[0,4], ymd[4,2]
if years[y].nil? or !years[y].include?(m)
categorized[c].delete(ymd)
end
end
categorized.delete(c) if categorized[c].empty?
end
rescue NoMethodError # when categorized[c] is nil
recreate(years)
retry
end
categorized
end | ruby | def categorize(category, years)
categories = category - ['ALL']
if categories.empty?
categories = restore_categories
else
categories &= restore_categories
end
categorized = {}
begin
categorized.clear
categories.each do |c|
@plugin.__send__(:transaction, 'category') do |db|
categorized[c] = get(db, c)
end
categorized[c].keys.each do |ymd|
y, m = ymd[0,4], ymd[4,2]
if years[y].nil? or !years[y].include?(m)
categorized[c].delete(ymd)
end
end
categorized.delete(c) if categorized[c].empty?
end
rescue NoMethodError # when categorized[c] is nil
recreate(years)
retry
end
categorized
end | [
"def",
"categorize",
"(",
"category",
",",
"years",
")",
"categories",
"=",
"category",
"-",
"[",
"'ALL'",
"]",
"if",
"categories",
".",
"empty?",
"categories",
"=",
"restore_categories",
"else",
"categories",
"&=",
"restore_categories",
"end",
"categorized",
"=",
"{",
"}",
"begin",
"categorized",
".",
"clear",
"categories",
".",
"each",
"do",
"|",
"c",
"|",
"@plugin",
".",
"__send__",
"(",
":transaction",
",",
"'category'",
")",
"do",
"|",
"db",
"|",
"categorized",
"[",
"c",
"]",
"=",
"get",
"(",
"db",
",",
"c",
")",
"end",
"categorized",
"[",
"c",
"]",
".",
"keys",
".",
"each",
"do",
"|",
"ymd",
"|",
"y",
",",
"m",
"=",
"ymd",
"[",
"0",
",",
"4",
"]",
",",
"ymd",
"[",
"4",
",",
"2",
"]",
"if",
"years",
"[",
"y",
"]",
".",
"nil?",
"or",
"!",
"years",
"[",
"y",
"]",
".",
"include?",
"(",
"m",
")",
"categorized",
"[",
"c",
"]",
".",
"delete",
"(",
"ymd",
")",
"end",
"end",
"categorized",
".",
"delete",
"(",
"c",
")",
"if",
"categorized",
"[",
"c",
"]",
".",
"empty?",
"end",
"rescue",
"NoMethodError",
"recreate",
"(",
"years",
")",
"retry",
"end",
"categorized",
"end"
]
| categorize sections of category of years
{"category" => {"yyyymmdd" => [[idx, title, excerpt], ...], ...}, ...} | [
"categorize",
"sections",
"of",
"category",
"of",
"years"
]
| 688b9378a872d6530ebd51788355fcd56b0f5b2d | https://github.com/tdiary/tdiary-core/blob/688b9378a872d6530ebd51788355fcd56b0f5b2d/misc/plugin/category-legacy.rb#L501-L530 | train |
tdiary/tdiary-core | misc/plugin/category-legacy.rb | Category.Cache.categorize_diary | def categorize_diary(diary)
categorized = {}
ymd = diary.date.strftime('%Y%m%d')
idx = 1
diary.each_section do |s|
shorten = begin
body = %Q|apply_plugin(#{s.body_to_html.dump}, true)|
@conf.shorten(eval(body, @binding))
rescue NameError
""
end
s.categories.each do |c|
categorized[c] = {} if categorized[c].nil?
categorized[c][ymd] = [] if categorized[c][ymd].nil?
categorized[c][ymd] << [idx, s.stripped_subtitle_to_html, shorten]
end
idx +=1
end
categorized
end | ruby | def categorize_diary(diary)
categorized = {}
ymd = diary.date.strftime('%Y%m%d')
idx = 1
diary.each_section do |s|
shorten = begin
body = %Q|apply_plugin(#{s.body_to_html.dump}, true)|
@conf.shorten(eval(body, @binding))
rescue NameError
""
end
s.categories.each do |c|
categorized[c] = {} if categorized[c].nil?
categorized[c][ymd] = [] if categorized[c][ymd].nil?
categorized[c][ymd] << [idx, s.stripped_subtitle_to_html, shorten]
end
idx +=1
end
categorized
end | [
"def",
"categorize_diary",
"(",
"diary",
")",
"categorized",
"=",
"{",
"}",
"ymd",
"=",
"diary",
".",
"date",
".",
"strftime",
"(",
"'%Y%m%d'",
")",
"idx",
"=",
"1",
"diary",
".",
"each_section",
"do",
"|",
"s",
"|",
"shorten",
"=",
"begin",
"body",
"=",
"%Q|apply_plugin(#{s.body_to_html.dump}, true)|",
"@conf",
".",
"shorten",
"(",
"eval",
"(",
"body",
",",
"@binding",
")",
")",
"rescue",
"NameError",
"\"\"",
"end",
"s",
".",
"categories",
".",
"each",
"do",
"|",
"c",
"|",
"categorized",
"[",
"c",
"]",
"=",
"{",
"}",
"if",
"categorized",
"[",
"c",
"]",
".",
"nil?",
"categorized",
"[",
"c",
"]",
"[",
"ymd",
"]",
"=",
"[",
"]",
"if",
"categorized",
"[",
"c",
"]",
"[",
"ymd",
"]",
".",
"nil?",
"categorized",
"[",
"c",
"]",
"[",
"ymd",
"]",
"<<",
"[",
"idx",
",",
"s",
".",
"stripped_subtitle_to_html",
",",
"shorten",
"]",
"end",
"idx",
"+=",
"1",
"end",
"categorized",
"end"
]
| categorize sections of diary
{"category" => {"yyyymmdd" => [[idx, title, excerpt], ...]}} | [
"categorize",
"sections",
"of",
"diary"
]
| 688b9378a872d6530ebd51788355fcd56b0f5b2d | https://github.com/tdiary/tdiary-core/blob/688b9378a872d6530ebd51788355fcd56b0f5b2d/misc/plugin/category-legacy.rb#L546-L567 | train |
tdiary/tdiary-core | lib/tdiary/dispatcher.rb | TDiary.Dispatcher.dispatch_cgi | def dispatch_cgi(request, cgi)
result = @target.run( request, cgi )
result.headers.reject!{|k,v| k.to_s.downcase == "status" }
result.to_a
end | ruby | def dispatch_cgi(request, cgi)
result = @target.run( request, cgi )
result.headers.reject!{|k,v| k.to_s.downcase == "status" }
result.to_a
end | [
"def",
"dispatch_cgi",
"(",
"request",
",",
"cgi",
")",
"result",
"=",
"@target",
".",
"run",
"(",
"request",
",",
"cgi",
")",
"result",
".",
"headers",
".",
"reject!",
"{",
"|",
"k",
",",
"v",
"|",
"k",
".",
"to_s",
".",
"downcase",
"==",
"\"status\"",
"}",
"result",
".",
"to_a",
"end"
]
| FIXME rename method name to more suitable one. | [
"FIXME",
"rename",
"method",
"name",
"to",
"more",
"suitable",
"one",
"."
]
| 688b9378a872d6530ebd51788355fcd56b0f5b2d | https://github.com/tdiary/tdiary-core/blob/688b9378a872d6530ebd51788355fcd56b0f5b2d/lib/tdiary/dispatcher.rb#L24-L28 | train |
tdiary/tdiary-core | lib/tdiary/dispatcher.rb | TDiary.Dispatcher.fake_stdin_as_params | def fake_stdin_as_params
stdin_spy = StringIO.new
if $RACK_ENV && $RACK_ENV['rack.input']
stdin_spy.print($RACK_ENV['rack.input'].read)
stdin_spy.rewind
end
$stdin = stdin_spy
end | ruby | def fake_stdin_as_params
stdin_spy = StringIO.new
if $RACK_ENV && $RACK_ENV['rack.input']
stdin_spy.print($RACK_ENV['rack.input'].read)
stdin_spy.rewind
end
$stdin = stdin_spy
end | [
"def",
"fake_stdin_as_params",
"stdin_spy",
"=",
"StringIO",
".",
"new",
"if",
"$RACK_ENV",
"&&",
"$RACK_ENV",
"[",
"'rack.input'",
"]",
"stdin_spy",
".",
"print",
"(",
"$RACK_ENV",
"[",
"'rack.input'",
"]",
".",
"read",
")",
"stdin_spy",
".",
"rewind",
"end",
"$stdin",
"=",
"stdin_spy",
"end"
]
| FIXME dirty hack | [
"FIXME",
"dirty",
"hack"
]
| 688b9378a872d6530ebd51788355fcd56b0f5b2d | https://github.com/tdiary/tdiary-core/blob/688b9378a872d6530ebd51788355fcd56b0f5b2d/lib/tdiary/dispatcher.rb#L80-L87 | train |
tdiary/tdiary-core | lib/tdiary/configuration.rb | TDiary.Configuration.load_cgi_conf | def load_cgi_conf
def_vars1 = ''
def_vars2 = ''
[
:tdiary_version,
:html_title, :author_name, :author_mail, :index_page, :hour_offset,
:description, :icon, :banner, :x_frame_options,
:header, :footer,
:section_anchor, :comment_anchor, :date_format, :latest_limit, :show_nyear,
:theme, :css,
:show_comment, :comment_limit, :comment_limit_per_day,
:mail_on_comment, :mail_header,
:show_referer, :no_referer2, :only_volatile2, :referer_table2,
:options2,
].each do |var|
def_vars1 << "#{var} = nil\n"
def_vars2 << "@#{var} = #{var} unless #{var} == nil\n"
end
unless defined?(::TDiary::Cache) && ::TDiary::Cache.method_defined?(:store_cache)
require 'tdiary/cache/file'
end
unless @io_class
require 'tdiary/io/default'
@io_class = IO::Default
attr_reader :io_class
end
cgi_conf = @io_class.load_cgi_conf(self)
b = binding
eval( def_vars1, b )
begin
eval( cgi_conf, b, "(TDiary::Configuration#load_cgi_conf)", 1 )
rescue SyntaxError
enc = case @lang
when 'en'
'UTF-8'
else
'EUC-JP'
end
cgi_conf.force_encoding( enc )
retry
end if cgi_conf
eval( def_vars2, b )
end | ruby | def load_cgi_conf
def_vars1 = ''
def_vars2 = ''
[
:tdiary_version,
:html_title, :author_name, :author_mail, :index_page, :hour_offset,
:description, :icon, :banner, :x_frame_options,
:header, :footer,
:section_anchor, :comment_anchor, :date_format, :latest_limit, :show_nyear,
:theme, :css,
:show_comment, :comment_limit, :comment_limit_per_day,
:mail_on_comment, :mail_header,
:show_referer, :no_referer2, :only_volatile2, :referer_table2,
:options2,
].each do |var|
def_vars1 << "#{var} = nil\n"
def_vars2 << "@#{var} = #{var} unless #{var} == nil\n"
end
unless defined?(::TDiary::Cache) && ::TDiary::Cache.method_defined?(:store_cache)
require 'tdiary/cache/file'
end
unless @io_class
require 'tdiary/io/default'
@io_class = IO::Default
attr_reader :io_class
end
cgi_conf = @io_class.load_cgi_conf(self)
b = binding
eval( def_vars1, b )
begin
eval( cgi_conf, b, "(TDiary::Configuration#load_cgi_conf)", 1 )
rescue SyntaxError
enc = case @lang
when 'en'
'UTF-8'
else
'EUC-JP'
end
cgi_conf.force_encoding( enc )
retry
end if cgi_conf
eval( def_vars2, b )
end | [
"def",
"load_cgi_conf",
"def_vars1",
"=",
"''",
"def_vars2",
"=",
"''",
"[",
":tdiary_version",
",",
":html_title",
",",
":author_name",
",",
":author_mail",
",",
":index_page",
",",
":hour_offset",
",",
":description",
",",
":icon",
",",
":banner",
",",
":x_frame_options",
",",
":header",
",",
":footer",
",",
":section_anchor",
",",
":comment_anchor",
",",
":date_format",
",",
":latest_limit",
",",
":show_nyear",
",",
":theme",
",",
":css",
",",
":show_comment",
",",
":comment_limit",
",",
":comment_limit_per_day",
",",
":mail_on_comment",
",",
":mail_header",
",",
":show_referer",
",",
":no_referer2",
",",
":only_volatile2",
",",
":referer_table2",
",",
":options2",
",",
"]",
".",
"each",
"do",
"|",
"var",
"|",
"def_vars1",
"<<",
"\"#{var} = nil\\n\"",
"def_vars2",
"<<",
"\"@#{var} = #{var} unless #{var} == nil\\n\"",
"end",
"unless",
"defined?",
"(",
"::",
"TDiary",
"::",
"Cache",
")",
"&&",
"::",
"TDiary",
"::",
"Cache",
".",
"method_defined?",
"(",
":store_cache",
")",
"require",
"'tdiary/cache/file'",
"end",
"unless",
"@io_class",
"require",
"'tdiary/io/default'",
"@io_class",
"=",
"IO",
"::",
"Default",
"attr_reader",
":io_class",
"end",
"cgi_conf",
"=",
"@io_class",
".",
"load_cgi_conf",
"(",
"self",
")",
"b",
"=",
"binding",
"eval",
"(",
"def_vars1",
",",
"b",
")",
"begin",
"eval",
"(",
"cgi_conf",
",",
"b",
",",
"\"(TDiary::Configuration#load_cgi_conf)\"",
",",
"1",
")",
"rescue",
"SyntaxError",
"enc",
"=",
"case",
"@lang",
"when",
"'en'",
"'UTF-8'",
"else",
"'EUC-JP'",
"end",
"cgi_conf",
".",
"force_encoding",
"(",
"enc",
")",
"retry",
"end",
"if",
"cgi_conf",
"eval",
"(",
"def_vars2",
",",
"b",
")",
"end"
]
| loading tdiary.conf in @data_path. | [
"loading",
"tdiary",
".",
"conf",
"in"
]
| 688b9378a872d6530ebd51788355fcd56b0f5b2d | https://github.com/tdiary/tdiary-core/blob/688b9378a872d6530ebd51788355fcd56b0f5b2d/lib/tdiary/configuration.rb#L83-L129 | train |
tdiary/tdiary-core | lib/tdiary/configuration.rb | TDiary.Configuration.configure_attrs | def configure_attrs
@options = {}
eval( File::open( 'tdiary.conf' ) {|f| f.read }, nil, "(tdiary.conf)", 1 )
# language setup
@lang = 'ja' unless @lang
begin
instance_eval( File::open( "#{TDiary::PATH}/tdiary/lang/#{@lang}.rb" ){|f| f.read }, "(tdiary/lang/#{@lang}.rb)", 1 )
rescue Errno::ENOENT
@lang = 'ja'
retry
end
@data_path += '/' if @data_path && /\/$/ !~ @data_path
@style = 'tDiary' unless @style
@index = './' unless @index
@update = 'update.rb' unless @update
@hide_comment_form = false unless defined?( @hide_comment_form )
@author_name = '' unless @author_name
@index_page = '' unless @index_page
@hour_offset = 0 unless @hour_offset
@html_title = '' unless @html_title
@x_frame_options = nil unless @x_frame_options
@header = '' unless @header
@footer = '' unless @footer
@section_anchor = '<span class="sanchor">_</span>' unless @section_anchor
@comment_anchor = '<span class="canchor">_</span>' unless @comment_anchor
@date_format = '%Y-%m-%d' unless @date_format
@latest_limit = 10 unless @latest_limit
@show_nyear = false unless @show_nyear
@theme = 'default' if not @theme and not @css
@theme = "local/#{@theme}" unless @theme.index('/')
@css = '' unless @css
@show_comment = true unless defined?( @show_comment )
@comment_limit = 3 unless @comment_limit
@comment_limit_per_day = 100 unless @comment_limit_per_day
@show_referer = true unless defined?( @show_referer )
@referer_limit = 10 unless @referer_limit
@referer_day_only = true unless defined?( @referer_day_only )
@no_referer = [] unless @no_referer
@no_referer2 = [] unless @no_referer2
@no_referer = @no_referer2 + @no_referer
@only_volatile = [] unless @only_volatile
@only_volatile2 = [] unless @only_volatile2
@only_volatile = @only_volatile2 + @only_volatile
@referer_table = [] unless @referer_table
@referer_table2 = [] unless @referer_table2
@referer_table = @referer_table2 + @referer_table
@options = {} unless @options.class == Hash
if @options2 then
@options.update( @options2 )
else
@options2 = {}
end
# for 1.4 compatibility
@section_anchor = @paragraph_anchor unless @section_anchor
end | ruby | def configure_attrs
@options = {}
eval( File::open( 'tdiary.conf' ) {|f| f.read }, nil, "(tdiary.conf)", 1 )
# language setup
@lang = 'ja' unless @lang
begin
instance_eval( File::open( "#{TDiary::PATH}/tdiary/lang/#{@lang}.rb" ){|f| f.read }, "(tdiary/lang/#{@lang}.rb)", 1 )
rescue Errno::ENOENT
@lang = 'ja'
retry
end
@data_path += '/' if @data_path && /\/$/ !~ @data_path
@style = 'tDiary' unless @style
@index = './' unless @index
@update = 'update.rb' unless @update
@hide_comment_form = false unless defined?( @hide_comment_form )
@author_name = '' unless @author_name
@index_page = '' unless @index_page
@hour_offset = 0 unless @hour_offset
@html_title = '' unless @html_title
@x_frame_options = nil unless @x_frame_options
@header = '' unless @header
@footer = '' unless @footer
@section_anchor = '<span class="sanchor">_</span>' unless @section_anchor
@comment_anchor = '<span class="canchor">_</span>' unless @comment_anchor
@date_format = '%Y-%m-%d' unless @date_format
@latest_limit = 10 unless @latest_limit
@show_nyear = false unless @show_nyear
@theme = 'default' if not @theme and not @css
@theme = "local/#{@theme}" unless @theme.index('/')
@css = '' unless @css
@show_comment = true unless defined?( @show_comment )
@comment_limit = 3 unless @comment_limit
@comment_limit_per_day = 100 unless @comment_limit_per_day
@show_referer = true unless defined?( @show_referer )
@referer_limit = 10 unless @referer_limit
@referer_day_only = true unless defined?( @referer_day_only )
@no_referer = [] unless @no_referer
@no_referer2 = [] unless @no_referer2
@no_referer = @no_referer2 + @no_referer
@only_volatile = [] unless @only_volatile
@only_volatile2 = [] unless @only_volatile2
@only_volatile = @only_volatile2 + @only_volatile
@referer_table = [] unless @referer_table
@referer_table2 = [] unless @referer_table2
@referer_table = @referer_table2 + @referer_table
@options = {} unless @options.class == Hash
if @options2 then
@options.update( @options2 )
else
@options2 = {}
end
# for 1.4 compatibility
@section_anchor = @paragraph_anchor unless @section_anchor
end | [
"def",
"configure_attrs",
"@options",
"=",
"{",
"}",
"eval",
"(",
"File",
"::",
"open",
"(",
"'tdiary.conf'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"read",
"}",
",",
"nil",
",",
"\"(tdiary.conf)\"",
",",
"1",
")",
"@lang",
"=",
"'ja'",
"unless",
"@lang",
"begin",
"instance_eval",
"(",
"File",
"::",
"open",
"(",
"\"#{TDiary::PATH}/tdiary/lang/#{@lang}.rb\"",
")",
"{",
"|",
"f",
"|",
"f",
".",
"read",
"}",
",",
"\"(tdiary/lang/#{@lang}.rb)\"",
",",
"1",
")",
"rescue",
"Errno",
"::",
"ENOENT",
"@lang",
"=",
"'ja'",
"retry",
"end",
"@data_path",
"+=",
"'/'",
"if",
"@data_path",
"&&",
"/",
"\\/",
"/",
"!~",
"@data_path",
"@style",
"=",
"'tDiary'",
"unless",
"@style",
"@index",
"=",
"'./'",
"unless",
"@index",
"@update",
"=",
"'update.rb'",
"unless",
"@update",
"@hide_comment_form",
"=",
"false",
"unless",
"defined?",
"(",
"@hide_comment_form",
")",
"@author_name",
"=",
"''",
"unless",
"@author_name",
"@index_page",
"=",
"''",
"unless",
"@index_page",
"@hour_offset",
"=",
"0",
"unless",
"@hour_offset",
"@html_title",
"=",
"''",
"unless",
"@html_title",
"@x_frame_options",
"=",
"nil",
"unless",
"@x_frame_options",
"@header",
"=",
"''",
"unless",
"@header",
"@footer",
"=",
"''",
"unless",
"@footer",
"@section_anchor",
"=",
"'<span class=\"sanchor\">_</span>'",
"unless",
"@section_anchor",
"@comment_anchor",
"=",
"'<span class=\"canchor\">_</span>'",
"unless",
"@comment_anchor",
"@date_format",
"=",
"'%Y-%m-%d'",
"unless",
"@date_format",
"@latest_limit",
"=",
"10",
"unless",
"@latest_limit",
"@show_nyear",
"=",
"false",
"unless",
"@show_nyear",
"@theme",
"=",
"'default'",
"if",
"not",
"@theme",
"and",
"not",
"@css",
"@theme",
"=",
"\"local/#{@theme}\"",
"unless",
"@theme",
".",
"index",
"(",
"'/'",
")",
"@css",
"=",
"''",
"unless",
"@css",
"@show_comment",
"=",
"true",
"unless",
"defined?",
"(",
"@show_comment",
")",
"@comment_limit",
"=",
"3",
"unless",
"@comment_limit",
"@comment_limit_per_day",
"=",
"100",
"unless",
"@comment_limit_per_day",
"@show_referer",
"=",
"true",
"unless",
"defined?",
"(",
"@show_referer",
")",
"@referer_limit",
"=",
"10",
"unless",
"@referer_limit",
"@referer_day_only",
"=",
"true",
"unless",
"defined?",
"(",
"@referer_day_only",
")",
"@no_referer",
"=",
"[",
"]",
"unless",
"@no_referer",
"@no_referer2",
"=",
"[",
"]",
"unless",
"@no_referer2",
"@no_referer",
"=",
"@no_referer2",
"+",
"@no_referer",
"@only_volatile",
"=",
"[",
"]",
"unless",
"@only_volatile",
"@only_volatile2",
"=",
"[",
"]",
"unless",
"@only_volatile2",
"@only_volatile",
"=",
"@only_volatile2",
"+",
"@only_volatile",
"@referer_table",
"=",
"[",
"]",
"unless",
"@referer_table",
"@referer_table2",
"=",
"[",
"]",
"unless",
"@referer_table2",
"@referer_table",
"=",
"@referer_table2",
"+",
"@referer_table",
"@options",
"=",
"{",
"}",
"unless",
"@options",
".",
"class",
"==",
"Hash",
"if",
"@options2",
"then",
"@options",
".",
"update",
"(",
"@options2",
")",
"else",
"@options2",
"=",
"{",
"}",
"end",
"@section_anchor",
"=",
"@paragraph_anchor",
"unless",
"@section_anchor",
"end"
]
| loading tdiary.conf in current directory | [
"loading",
"tdiary",
".",
"conf",
"in",
"current",
"directory"
]
| 688b9378a872d6530ebd51788355fcd56b0f5b2d | https://github.com/tdiary/tdiary-core/blob/688b9378a872d6530ebd51788355fcd56b0f5b2d/lib/tdiary/configuration.rb#L132-L197 | train |
josevalim/rails-footnotes | lib/rails-footnotes/filter.rb | Footnotes.Filter.close! | def close!(controller)
self.each_with_rescue(@@klasses) {|klass| klass.close!(controller)}
self.each_with_rescue(Footnotes.after_hooks) {|hook| hook.call(controller, self)}
end | ruby | def close!(controller)
self.each_with_rescue(@@klasses) {|klass| klass.close!(controller)}
self.each_with_rescue(Footnotes.after_hooks) {|hook| hook.call(controller, self)}
end | [
"def",
"close!",
"(",
"controller",
")",
"self",
".",
"each_with_rescue",
"(",
"@@klasses",
")",
"{",
"|",
"klass",
"|",
"klass",
".",
"close!",
"(",
"controller",
")",
"}",
"self",
".",
"each_with_rescue",
"(",
"Footnotes",
".",
"after_hooks",
")",
"{",
"|",
"hook",
"|",
"hook",
".",
"call",
"(",
"controller",
",",
"self",
")",
"}",
"end"
]
| Calls the class method close! in each note
Sometimes notes need to finish their work even after being read
This method allows this kind of work | [
"Calls",
"the",
"class",
"method",
"close!",
"in",
"each",
"note",
"Sometimes",
"notes",
"need",
"to",
"finish",
"their",
"work",
"even",
"after",
"being",
"read",
"This",
"method",
"allows",
"this",
"kind",
"of",
"work"
]
| 0ca9f4c4ce404113994f81552c304d8fd326ac1c | https://github.com/josevalim/rails-footnotes/blob/0ca9f4c4ce404113994f81552c304d8fd326ac1c/lib/rails-footnotes/filter.rb#L83-L86 | train |
josevalim/rails-footnotes | lib/rails-footnotes/filter.rb | Footnotes.Filter.close | def close
javascript = ''
each_with_rescue(@notes) do |note|
next unless note.has_fieldset?
javascript << close_helper(note)
end
javascript
end | ruby | def close
javascript = ''
each_with_rescue(@notes) do |note|
next unless note.has_fieldset?
javascript << close_helper(note)
end
javascript
end | [
"def",
"close",
"javascript",
"=",
"''",
"each_with_rescue",
"(",
"@notes",
")",
"do",
"|",
"note",
"|",
"next",
"unless",
"note",
".",
"has_fieldset?",
"javascript",
"<<",
"close_helper",
"(",
"note",
")",
"end",
"javascript",
"end"
]
| Process notes to get javascript code to close them.
This method is only used when multiple_notes is false. | [
"Process",
"notes",
"to",
"get",
"javascript",
"code",
"to",
"close",
"them",
".",
"This",
"method",
"is",
"only",
"used",
"when",
"multiple_notes",
"is",
"false",
"."
]
| 0ca9f4c4ce404113994f81552c304d8fd326ac1c | https://github.com/josevalim/rails-footnotes/blob/0ca9f4c4ce404113994f81552c304d8fd326ac1c/lib/rails-footnotes/filter.rb#L300-L307 | train |
josevalim/rails-footnotes | lib/rails-footnotes/filter.rb | Footnotes.Filter.link_helper | def link_helper(note)
onclick = note.onclick
unless href = note.link
href = '#'
onclick ||= "Footnotes.hideAllAndToggle('#{note.to_sym}_debug_info');return false;" if note.has_fieldset?
end
"<a href=\"#{href}\" onclick=\"#{onclick}\">#{note.title}</a>"
end | ruby | def link_helper(note)
onclick = note.onclick
unless href = note.link
href = '#'
onclick ||= "Footnotes.hideAllAndToggle('#{note.to_sym}_debug_info');return false;" if note.has_fieldset?
end
"<a href=\"#{href}\" onclick=\"#{onclick}\">#{note.title}</a>"
end | [
"def",
"link_helper",
"(",
"note",
")",
"onclick",
"=",
"note",
".",
"onclick",
"unless",
"href",
"=",
"note",
".",
"link",
"href",
"=",
"'#'",
"onclick",
"||=",
"\"Footnotes.hideAllAndToggle('#{note.to_sym}_debug_info');return false;\"",
"if",
"note",
".",
"has_fieldset?",
"end",
"\"<a href=\\\"#{href}\\\" onclick=\\\"#{onclick}\\\">#{note.title}</a>\"",
"end"
]
| Helper that creates the link and javascript code when note is clicked | [
"Helper",
"that",
"creates",
"the",
"link",
"and",
"javascript",
"code",
"when",
"note",
"is",
"clicked"
]
| 0ca9f4c4ce404113994f81552c304d8fd326ac1c | https://github.com/josevalim/rails-footnotes/blob/0ca9f4c4ce404113994f81552c304d8fd326ac1c/lib/rails-footnotes/filter.rb#L321-L329 | train |
apache/predictionio-sdk-ruby | lib/predictionio/connection.rb | PredictionIO.Connection.request | def request(method, request)
response = AsyncResponse.new(request)
@packages.push(method: method, request: request, response: response)
response
end | ruby | def request(method, request)
response = AsyncResponse.new(request)
@packages.push(method: method, request: request, response: response)
response
end | [
"def",
"request",
"(",
"method",
",",
"request",
")",
"response",
"=",
"AsyncResponse",
".",
"new",
"(",
"request",
")",
"@packages",
".",
"push",
"(",
"method",
":",
"method",
",",
"request",
":",
"request",
",",
"response",
":",
"response",
")",
"response",
"end"
]
| Spawns a number of threads with persistent HTTP connection to the specified URI.
Sets a default timeout of 60 seconds.
Create an asynchronous request and response package, put it in the pending queue, and return the response object. | [
"Spawns",
"a",
"number",
"of",
"threads",
"with",
"persistent",
"HTTP",
"connection",
"to",
"the",
"specified",
"URI",
".",
"Sets",
"a",
"default",
"timeout",
"of",
"60",
"seconds",
".",
"Create",
"an",
"asynchronous",
"request",
"and",
"response",
"package",
"put",
"it",
"in",
"the",
"pending",
"queue",
"and",
"return",
"the",
"response",
"object",
"."
]
| a1777db9f89a4287d252c8ca166a279fb2af64b7 | https://github.com/apache/predictionio-sdk-ruby/blob/a1777db9f89a4287d252c8ca166a279fb2af64b7/lib/predictionio/connection.rb#L108-L112 | train |
apache/predictionio-sdk-ruby | lib/predictionio/event_client.rb | PredictionIO.EventClient.get_status | def get_status
status = @http.aget(PredictionIO::AsyncRequest.new('/')).get
begin
status.body
rescue
status
end
end | ruby | def get_status
status = @http.aget(PredictionIO::AsyncRequest.new('/')).get
begin
status.body
rescue
status
end
end | [
"def",
"get_status",
"status",
"=",
"@http",
".",
"aget",
"(",
"PredictionIO",
"::",
"AsyncRequest",
".",
"new",
"(",
"'/'",
")",
")",
".",
"get",
"begin",
"status",
".",
"body",
"rescue",
"status",
"end",
"end"
]
| Returns PredictionIO's status in string. | [
"Returns",
"PredictionIO",
"s",
"status",
"in",
"string",
"."
]
| a1777db9f89a4287d252c8ca166a279fb2af64b7 | https://github.com/apache/predictionio-sdk-ruby/blob/a1777db9f89a4287d252c8ca166a279fb2af64b7/lib/predictionio/event_client.rb#L112-L119 | train |
remvee/exifr | lib/exifr/jpeg.rb | EXIFR.JPEG.to_hash | def to_hash
h = {:width => width, :height => height, :bits => bits, :comment => comment}
h.merge!(exif) if exif?
h
end | ruby | def to_hash
h = {:width => width, :height => height, :bits => bits, :comment => comment}
h.merge!(exif) if exif?
h
end | [
"def",
"to_hash",
"h",
"=",
"{",
":width",
"=>",
"width",
",",
":height",
"=>",
"height",
",",
":bits",
"=>",
"bits",
",",
":comment",
"=>",
"comment",
"}",
"h",
".",
"merge!",
"(",
"exif",
")",
"if",
"exif?",
"h",
"end"
]
| Get a hash presentation of the image. | [
"Get",
"a",
"hash",
"presentation",
"of",
"the",
"image",
"."
]
| 1e7b29befed53be8e0bd59fc62e4a98ca603c44a | https://github.com/remvee/exifr/blob/1e7b29befed53be8e0bd59fc62e4a98ca603c44a/lib/exifr/jpeg.rb#L51-L55 | train |
remvee/exifr | lib/exifr/jpeg.rb | EXIFR.JPEG.method_missing | def method_missing(method, *args)
super unless args.empty?
super unless methods.include?(method)
@exif.send method if defined?(@exif) && @exif
end | ruby | def method_missing(method, *args)
super unless args.empty?
super unless methods.include?(method)
@exif.send method if defined?(@exif) && @exif
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
")",
"super",
"unless",
"args",
".",
"empty?",
"super",
"unless",
"methods",
".",
"include?",
"(",
"method",
")",
"@exif",
".",
"send",
"method",
"if",
"defined?",
"(",
"@exif",
")",
"&&",
"@exif",
"end"
]
| Dispatch to EXIF. When no EXIF data is available but the
+method+ does exist for EXIF data +nil+ will be returned. | [
"Dispatch",
"to",
"EXIF",
".",
"When",
"no",
"EXIF",
"data",
"is",
"available",
"but",
"the",
"+",
"method",
"+",
"does",
"exist",
"for",
"EXIF",
"data",
"+",
"nil",
"+",
"will",
"be",
"returned",
"."
]
| 1e7b29befed53be8e0bd59fc62e4a98ca603c44a | https://github.com/remvee/exifr/blob/1e7b29befed53be8e0bd59fc62e4a98ca603c44a/lib/exifr/jpeg.rb#L59-L63 | train |
remvee/exifr | lib/exifr/tiff.rb | EXIFR.TIFF.method_missing | def method_missing(method, *args)
super unless args.empty?
if @ifds.first.respond_to?(method)
@ifds.first.send(method)
elsif TAGS.include?(method)
@ifds.first.to_hash[method]
else
super
end
end | ruby | def method_missing(method, *args)
super unless args.empty?
if @ifds.first.respond_to?(method)
@ifds.first.send(method)
elsif TAGS.include?(method)
@ifds.first.to_hash[method]
else
super
end
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
")",
"super",
"unless",
"args",
".",
"empty?",
"if",
"@ifds",
".",
"first",
".",
"respond_to?",
"(",
"method",
")",
"@ifds",
".",
"first",
".",
"send",
"(",
"method",
")",
"elsif",
"TAGS",
".",
"include?",
"(",
"method",
")",
"@ifds",
".",
"first",
".",
"to_hash",
"[",
"method",
"]",
"else",
"super",
"end",
"end"
]
| Dispatch to first image. | [
"Dispatch",
"to",
"first",
"image",
"."
]
| 1e7b29befed53be8e0bd59fc62e4a98ca603c44a | https://github.com/remvee/exifr/blob/1e7b29befed53be8e0bd59fc62e4a98ca603c44a/lib/exifr/tiff.rb#L409-L419 | train |
remvee/exifr | lib/exifr/tiff.rb | EXIFR.TIFF.gps | def gps
return nil unless gps_latitude && gps_longitude
altitude = gps_altitude.is_a?(Array) ? gps_altitude.first : gps_altitude
GPS.new(gps_latitude.to_f * (gps_latitude_ref == 'S' ? -1 : 1),
gps_longitude.to_f * (gps_longitude_ref == 'W' ? -1 : 1),
altitude && (altitude.to_f * (gps_altitude_ref == "\1" ? -1 : 1)),
gps_img_direction && gps_img_direction.to_f)
end | ruby | def gps
return nil unless gps_latitude && gps_longitude
altitude = gps_altitude.is_a?(Array) ? gps_altitude.first : gps_altitude
GPS.new(gps_latitude.to_f * (gps_latitude_ref == 'S' ? -1 : 1),
gps_longitude.to_f * (gps_longitude_ref == 'W' ? -1 : 1),
altitude && (altitude.to_f * (gps_altitude_ref == "\1" ? -1 : 1)),
gps_img_direction && gps_img_direction.to_f)
end | [
"def",
"gps",
"return",
"nil",
"unless",
"gps_latitude",
"&&",
"gps_longitude",
"altitude",
"=",
"gps_altitude",
".",
"is_a?",
"(",
"Array",
")",
"?",
"gps_altitude",
".",
"first",
":",
"gps_altitude",
"GPS",
".",
"new",
"(",
"gps_latitude",
".",
"to_f",
"*",
"(",
"gps_latitude_ref",
"==",
"'S'",
"?",
"-",
"1",
":",
"1",
")",
",",
"gps_longitude",
".",
"to_f",
"*",
"(",
"gps_longitude_ref",
"==",
"'W'",
"?",
"-",
"1",
":",
"1",
")",
",",
"altitude",
"&&",
"(",
"altitude",
".",
"to_f",
"*",
"(",
"gps_altitude_ref",
"==",
"\"\\1\"",
"?",
"-",
"1",
":",
"1",
")",
")",
",",
"gps_img_direction",
"&&",
"gps_img_direction",
".",
"to_f",
")",
"end"
]
| Get GPS location, altitude and image direction return nil when not available. | [
"Get",
"GPS",
"location",
"altitude",
"and",
"image",
"direction",
"return",
"nil",
"when",
"not",
"available",
"."
]
| 1e7b29befed53be8e0bd59fc62e4a98ca603c44a | https://github.com/remvee/exifr/blob/1e7b29befed53be8e0bd59fc62e4a98ca603c44a/lib/exifr/tiff.rb#L462-L471 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.