repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
mikel/mail | lib/mail/network/delivery_methods/smtp_connection.rb | Mail.SMTPConnection.deliver! | def deliver!(mail)
envelope = Mail::SmtpEnvelope.new(mail)
response = smtp.sendmail(dot_stuff(envelope.message), envelope.from, envelope.to)
settings[:return_response] ? response : self
end | ruby | def deliver!(mail)
envelope = Mail::SmtpEnvelope.new(mail)
response = smtp.sendmail(dot_stuff(envelope.message), envelope.from, envelope.to)
settings[:return_response] ? response : self
end | [
"def",
"deliver!",
"(",
"mail",
")",
"envelope",
"=",
"Mail",
"::",
"SmtpEnvelope",
".",
"new",
"(",
"mail",
")",
"response",
"=",
"smtp",
".",
"sendmail",
"(",
"dot_stuff",
"(",
"envelope",
".",
"message",
")",
",",
"envelope",
".",
"from",
",",
"envelope",
".",
"to",
")",
"settings",
"[",
":return_response",
"]",
"?",
"response",
":",
"self",
"end"
] | Send the message via SMTP.
The from and to attributes are optional. If not set, they are retrieve from the Message. | [
"Send",
"the",
"message",
"via",
"SMTP",
".",
"The",
"from",
"and",
"to",
"attributes",
"are",
"optional",
".",
"If",
"not",
"set",
"they",
"are",
"retrieve",
"from",
"the",
"Message",
"."
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/network/delivery_methods/smtp_connection.rb#L51-L55 | train |
mikel/mail | lib/mail/fields/content_type_field.rb | Mail.ContentTypeField.sanitize | def sanitize(val)
# TODO: check if there are cases where whitespace is not a separator
val = val.
gsub(/\s*=\s*/,'='). # remove whitespaces around equal sign
gsub(/[; ]+/, '; '). #use '; ' as a separator (or EOL)
gsub(/;\s*$/,'') #remove trailing to keep examples below
if val =~ /(boundary=(\S*))/i
val = "#{$`.downcase}boundary=#{$2}#{$'.downcase}"
else
val.downcase!
end
case
when val.chomp =~ /^\s*([\w\-]+)\/([\w\-]+)\s*;\s?(ISO[\w\-]+)$/i
# Microsoft helper:
# Handles 'type/subtype;ISO-8559-1'
"#{$1}/#{$2}; charset=#{Utilities.quote_atom($3)}"
when val.chomp =~ /^text;?$/i
# Handles 'text;' and 'text'
"text/plain;"
when val.chomp =~ /^(\w+);\s(.*)$/i
# Handles 'text; <parameters>'
"text/plain; #{$2}"
when val =~ /([\w\-]+\/[\w\-]+);\scharset="charset="(\w+)""/i
# Handles text/html; charset="charset="GB2312""
"#{$1}; charset=#{Utilities.quote_atom($2)}"
when val =~ /([\w\-]+\/[\w\-]+);\s+(.*)/i
type = $1
# Handles misquoted param values
# e.g: application/octet-stream; name=archiveshelp1[1].htm
# and: audio/x-midi;\r\n\sname=Part .exe
params = $2.to_s.split(/\s+/)
params = params.map { |i| i.to_s.chomp.strip }
params = params.map { |i| i.split(/\s*\=\s*/, 2) }
params = params.map { |i| "#{i[0]}=#{Utilities.dquote(i[1].to_s.gsub(/;$/,""))}" }.join('; ')
"#{type}; #{params}"
when val =~ /^\s*$/
'text/plain'
else
val
end
end | ruby | def sanitize(val)
# TODO: check if there are cases where whitespace is not a separator
val = val.
gsub(/\s*=\s*/,'='). # remove whitespaces around equal sign
gsub(/[; ]+/, '; '). #use '; ' as a separator (or EOL)
gsub(/;\s*$/,'') #remove trailing to keep examples below
if val =~ /(boundary=(\S*))/i
val = "#{$`.downcase}boundary=#{$2}#{$'.downcase}"
else
val.downcase!
end
case
when val.chomp =~ /^\s*([\w\-]+)\/([\w\-]+)\s*;\s?(ISO[\w\-]+)$/i
# Microsoft helper:
# Handles 'type/subtype;ISO-8559-1'
"#{$1}/#{$2}; charset=#{Utilities.quote_atom($3)}"
when val.chomp =~ /^text;?$/i
# Handles 'text;' and 'text'
"text/plain;"
when val.chomp =~ /^(\w+);\s(.*)$/i
# Handles 'text; <parameters>'
"text/plain; #{$2}"
when val =~ /([\w\-]+\/[\w\-]+);\scharset="charset="(\w+)""/i
# Handles text/html; charset="charset="GB2312""
"#{$1}; charset=#{Utilities.quote_atom($2)}"
when val =~ /([\w\-]+\/[\w\-]+);\s+(.*)/i
type = $1
# Handles misquoted param values
# e.g: application/octet-stream; name=archiveshelp1[1].htm
# and: audio/x-midi;\r\n\sname=Part .exe
params = $2.to_s.split(/\s+/)
params = params.map { |i| i.to_s.chomp.strip }
params = params.map { |i| i.split(/\s*\=\s*/, 2) }
params = params.map { |i| "#{i[0]}=#{Utilities.dquote(i[1].to_s.gsub(/;$/,""))}" }.join('; ')
"#{type}; #{params}"
when val =~ /^\s*$/
'text/plain'
else
val
end
end | [
"def",
"sanitize",
"(",
"val",
")",
"# TODO: check if there are cases where whitespace is not a separator",
"val",
"=",
"val",
".",
"gsub",
"(",
"/",
"\\s",
"\\s",
"/",
",",
"'='",
")",
".",
"# remove whitespaces around equal sign",
"gsub",
"(",
"/",
"/",
",",
"'; '",
")",
".",
"#use '; ' as a separator (or EOL)",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"''",
")",
"#remove trailing to keep examples below",
"if",
"val",
"=~",
"/",
"\\S",
"/i",
"val",
"=",
"\"#{$`.downcase}boundary=#{$2}#{$'.downcase}\"",
"else",
"val",
".",
"downcase!",
"end",
"case",
"when",
"val",
".",
"chomp",
"=~",
"/",
"\\s",
"\\w",
"\\-",
"\\/",
"\\w",
"\\-",
"\\s",
"\\s",
"\\w",
"\\-",
"/i",
"# Microsoft helper:",
"# Handles 'type/subtype;ISO-8559-1'",
"\"#{$1}/#{$2}; charset=#{Utilities.quote_atom($3)}\"",
"when",
"val",
".",
"chomp",
"=~",
"/",
"/i",
"# Handles 'text;' and 'text'",
"\"text/plain;\"",
"when",
"val",
".",
"chomp",
"=~",
"/",
"\\w",
"\\s",
"/i",
"# Handles 'text; <parameters>'",
"\"text/plain; #{$2}\"",
"when",
"val",
"=~",
"/",
"\\w",
"\\-",
"\\/",
"\\w",
"\\-",
"\\s",
"\\w",
"/i",
"# Handles text/html; charset=\"charset=\"GB2312\"\"",
"\"#{$1}; charset=#{Utilities.quote_atom($2)}\"",
"when",
"val",
"=~",
"/",
"\\w",
"\\-",
"\\/",
"\\w",
"\\-",
"\\s",
"/i",
"type",
"=",
"$1",
"# Handles misquoted param values",
"# e.g: application/octet-stream; name=archiveshelp1[1].htm",
"# and: audio/x-midi;\\r\\n\\sname=Part .exe",
"params",
"=",
"$2",
".",
"to_s",
".",
"split",
"(",
"/",
"\\s",
"/",
")",
"params",
"=",
"params",
".",
"map",
"{",
"|",
"i",
"|",
"i",
".",
"to_s",
".",
"chomp",
".",
"strip",
"}",
"params",
"=",
"params",
".",
"map",
"{",
"|",
"i",
"|",
"i",
".",
"split",
"(",
"/",
"\\s",
"\\=",
"\\s",
"/",
",",
"2",
")",
"}",
"params",
"=",
"params",
".",
"map",
"{",
"|",
"i",
"|",
"\"#{i[0]}=#{Utilities.dquote(i[1].to_s.gsub(/;$/,\"\"))}\"",
"}",
".",
"join",
"(",
"'; '",
")",
"\"#{type}; #{params}\"",
"when",
"val",
"=~",
"/",
"\\s",
"/",
"'text/plain'",
"else",
"val",
"end",
"end"
] | Various special cases from random emails found that I am not going to change
the parser for | [
"Various",
"special",
"cases",
"from",
"random",
"emails",
"found",
"that",
"I",
"am",
"not",
"going",
"to",
"change",
"the",
"parser",
"for"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/fields/content_type_field.rb#L119-L161 | train |
mikel/mail | lib/mail/utilities.rb | Mail.Utilities.quote_phrase | def quote_phrase( str )
if str.respond_to?(:force_encoding)
original_encoding = str.encoding
ascii_str = str.to_s.dup.force_encoding('ASCII-8BIT')
if Constants::PHRASE_UNSAFE === ascii_str
dquote(ascii_str).force_encoding(original_encoding)
else
str
end
else
Constants::PHRASE_UNSAFE === str ? dquote(str) : str
end
end | ruby | def quote_phrase( str )
if str.respond_to?(:force_encoding)
original_encoding = str.encoding
ascii_str = str.to_s.dup.force_encoding('ASCII-8BIT')
if Constants::PHRASE_UNSAFE === ascii_str
dquote(ascii_str).force_encoding(original_encoding)
else
str
end
else
Constants::PHRASE_UNSAFE === str ? dquote(str) : str
end
end | [
"def",
"quote_phrase",
"(",
"str",
")",
"if",
"str",
".",
"respond_to?",
"(",
":force_encoding",
")",
"original_encoding",
"=",
"str",
".",
"encoding",
"ascii_str",
"=",
"str",
".",
"to_s",
".",
"dup",
".",
"force_encoding",
"(",
"'ASCII-8BIT'",
")",
"if",
"Constants",
"::",
"PHRASE_UNSAFE",
"===",
"ascii_str",
"dquote",
"(",
"ascii_str",
")",
".",
"force_encoding",
"(",
"original_encoding",
")",
"else",
"str",
"end",
"else",
"Constants",
"::",
"PHRASE_UNSAFE",
"===",
"str",
"?",
"dquote",
"(",
"str",
")",
":",
"str",
"end",
"end"
] | If the string supplied has PHRASE unsafe characters in it, will return the string quoted
in double quotes, otherwise returns the string unmodified | [
"If",
"the",
"string",
"supplied",
"has",
"PHRASE",
"unsafe",
"characters",
"in",
"it",
"will",
"return",
"the",
"string",
"quoted",
"in",
"double",
"quotes",
"otherwise",
"returns",
"the",
"string",
"unmodified"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/utilities.rb#L23-L35 | train |
mikel/mail | lib/mail/utilities.rb | Mail.Utilities.quote_token | def quote_token( str )
if str.respond_to?(:force_encoding)
original_encoding = str.encoding
ascii_str = str.to_s.dup.force_encoding('ASCII-8BIT')
if token_safe?( ascii_str )
str
else
dquote(ascii_str).force_encoding(original_encoding)
end
else
token_safe?( str ) ? str : dquote(str)
end
end | ruby | def quote_token( str )
if str.respond_to?(:force_encoding)
original_encoding = str.encoding
ascii_str = str.to_s.dup.force_encoding('ASCII-8BIT')
if token_safe?( ascii_str )
str
else
dquote(ascii_str).force_encoding(original_encoding)
end
else
token_safe?( str ) ? str : dquote(str)
end
end | [
"def",
"quote_token",
"(",
"str",
")",
"if",
"str",
".",
"respond_to?",
"(",
":force_encoding",
")",
"original_encoding",
"=",
"str",
".",
"encoding",
"ascii_str",
"=",
"str",
".",
"to_s",
".",
"dup",
".",
"force_encoding",
"(",
"'ASCII-8BIT'",
")",
"if",
"token_safe?",
"(",
"ascii_str",
")",
"str",
"else",
"dquote",
"(",
"ascii_str",
")",
".",
"force_encoding",
"(",
"original_encoding",
")",
"end",
"else",
"token_safe?",
"(",
"str",
")",
"?",
"str",
":",
"dquote",
"(",
"str",
")",
"end",
"end"
] | If the string supplied has TOKEN unsafe characters in it, will return the string quoted
in double quotes, otherwise returns the string unmodified | [
"If",
"the",
"string",
"supplied",
"has",
"TOKEN",
"unsafe",
"characters",
"in",
"it",
"will",
"return",
"the",
"string",
"quoted",
"in",
"double",
"quotes",
"otherwise",
"returns",
"the",
"string",
"unmodified"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/utilities.rb#L44-L56 | train |
mikel/mail | lib/mail/utilities.rb | Mail.Utilities.capitalize_field | def capitalize_field( str )
str.to_s.split("-").map { |v| v.capitalize }.join("-")
end | ruby | def capitalize_field( str )
str.to_s.split("-").map { |v| v.capitalize }.join("-")
end | [
"def",
"capitalize_field",
"(",
"str",
")",
"str",
".",
"to_s",
".",
"split",
"(",
"\"-\"",
")",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"capitalize",
"}",
".",
"join",
"(",
"\"-\"",
")",
"end"
] | Capitalizes a string that is joined by hyphens correctly.
Example:
string = 'resent-from-field'
capitalize_field( string ) #=> 'Resent-From-Field' | [
"Capitalizes",
"a",
"string",
"that",
"is",
"joined",
"by",
"hyphens",
"correctly",
"."
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/utilities.rb#L188-L190 | train |
mikel/mail | lib/mail/utilities.rb | Mail.Utilities.constantize | def constantize( str )
str.to_s.split(/[-_]/).map { |v| v.capitalize }.to_s
end | ruby | def constantize( str )
str.to_s.split(/[-_]/).map { |v| v.capitalize }.to_s
end | [
"def",
"constantize",
"(",
"str",
")",
"str",
".",
"to_s",
".",
"split",
"(",
"/",
"/",
")",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"capitalize",
"}",
".",
"to_s",
"end"
] | Takes an underscored word and turns it into a class name
Example:
constantize("hello") #=> "Hello"
constantize("hello-there") #=> "HelloThere"
constantize("hello-there-mate") #=> "HelloThereMate" | [
"Takes",
"an",
"underscored",
"word",
"and",
"turns",
"it",
"into",
"a",
"class",
"name"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/utilities.rb#L199-L201 | train |
mikel/mail | lib/mail/utilities.rb | Mail.Utilities.blank? | def blank?(value)
if value.kind_of?(NilClass)
true
elsif value.kind_of?(String)
value !~ /\S/
else
value.respond_to?(:empty?) ? value.empty? : !value
end
end | ruby | def blank?(value)
if value.kind_of?(NilClass)
true
elsif value.kind_of?(String)
value !~ /\S/
else
value.respond_to?(:empty?) ? value.empty? : !value
end
end | [
"def",
"blank?",
"(",
"value",
")",
"if",
"value",
".",
"kind_of?",
"(",
"NilClass",
")",
"true",
"elsif",
"value",
".",
"kind_of?",
"(",
"String",
")",
"value",
"!~",
"/",
"\\S",
"/",
"else",
"value",
".",
"respond_to?",
"(",
":empty?",
")",
"?",
"value",
".",
"empty?",
":",
"!",
"value",
"end",
"end"
] | Returns true if the object is considered blank.
A blank includes things like '', ' ', nil,
and arrays and hashes that have nothing in them.
This logic is mostly shared with ActiveSupport's blank? | [
"Returns",
"true",
"if",
"the",
"object",
"is",
"considered",
"blank",
".",
"A",
"blank",
"includes",
"things",
"like",
"nil",
"and",
"arrays",
"and",
"hashes",
"that",
"have",
"nothing",
"in",
"them",
"."
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/utilities.rb#L315-L323 | train |
mikel/mail | lib/mail/network/retriever_methods/imap.rb | Mail.IMAP.find | def find(options=nil, &block)
options = validate_options(options)
start do |imap|
options[:read_only] ? imap.examine(options[:mailbox]) : imap.select(options[:mailbox])
uids = imap.uid_search(options[:keys], options[:search_charset])
uids.reverse! if options[:what].to_sym == :last
uids = uids.first(options[:count]) if options[:count].is_a?(Integer)
uids.reverse! if (options[:what].to_sym == :last && options[:order].to_sym == :asc) ||
(options[:what].to_sym != :last && options[:order].to_sym == :desc)
if block_given?
uids.each do |uid|
uid = options[:uid].to_i unless options[:uid].nil?
fetchdata = imap.uid_fetch(uid, ['RFC822', 'FLAGS'])[0]
new_message = Mail.new(fetchdata.attr['RFC822'])
new_message.mark_for_delete = true if options[:delete_after_find]
if block.arity == 4
yield new_message, imap, uid, fetchdata.attr['FLAGS']
elsif block.arity == 3
yield new_message, imap, uid
else
yield new_message
end
imap.uid_store(uid, "+FLAGS", [Net::IMAP::DELETED]) if options[:delete_after_find] && new_message.is_marked_for_delete?
break unless options[:uid].nil?
end
imap.expunge if options[:delete_after_find]
else
emails = []
uids.each do |uid|
uid = options[:uid].to_i unless options[:uid].nil?
fetchdata = imap.uid_fetch(uid, ['RFC822'])[0]
emails << Mail.new(fetchdata.attr['RFC822'])
imap.uid_store(uid, "+FLAGS", [Net::IMAP::DELETED]) if options[:delete_after_find]
break unless options[:uid].nil?
end
imap.expunge if options[:delete_after_find]
emails.size == 1 && options[:count] == 1 ? emails.first : emails
end
end
end | ruby | def find(options=nil, &block)
options = validate_options(options)
start do |imap|
options[:read_only] ? imap.examine(options[:mailbox]) : imap.select(options[:mailbox])
uids = imap.uid_search(options[:keys], options[:search_charset])
uids.reverse! if options[:what].to_sym == :last
uids = uids.first(options[:count]) if options[:count].is_a?(Integer)
uids.reverse! if (options[:what].to_sym == :last && options[:order].to_sym == :asc) ||
(options[:what].to_sym != :last && options[:order].to_sym == :desc)
if block_given?
uids.each do |uid|
uid = options[:uid].to_i unless options[:uid].nil?
fetchdata = imap.uid_fetch(uid, ['RFC822', 'FLAGS'])[0]
new_message = Mail.new(fetchdata.attr['RFC822'])
new_message.mark_for_delete = true if options[:delete_after_find]
if block.arity == 4
yield new_message, imap, uid, fetchdata.attr['FLAGS']
elsif block.arity == 3
yield new_message, imap, uid
else
yield new_message
end
imap.uid_store(uid, "+FLAGS", [Net::IMAP::DELETED]) if options[:delete_after_find] && new_message.is_marked_for_delete?
break unless options[:uid].nil?
end
imap.expunge if options[:delete_after_find]
else
emails = []
uids.each do |uid|
uid = options[:uid].to_i unless options[:uid].nil?
fetchdata = imap.uid_fetch(uid, ['RFC822'])[0]
emails << Mail.new(fetchdata.attr['RFC822'])
imap.uid_store(uid, "+FLAGS", [Net::IMAP::DELETED]) if options[:delete_after_find]
break unless options[:uid].nil?
end
imap.expunge if options[:delete_after_find]
emails.size == 1 && options[:count] == 1 ? emails.first : emails
end
end
end | [
"def",
"find",
"(",
"options",
"=",
"nil",
",",
"&",
"block",
")",
"options",
"=",
"validate_options",
"(",
"options",
")",
"start",
"do",
"|",
"imap",
"|",
"options",
"[",
":read_only",
"]",
"?",
"imap",
".",
"examine",
"(",
"options",
"[",
":mailbox",
"]",
")",
":",
"imap",
".",
"select",
"(",
"options",
"[",
":mailbox",
"]",
")",
"uids",
"=",
"imap",
".",
"uid_search",
"(",
"options",
"[",
":keys",
"]",
",",
"options",
"[",
":search_charset",
"]",
")",
"uids",
".",
"reverse!",
"if",
"options",
"[",
":what",
"]",
".",
"to_sym",
"==",
":last",
"uids",
"=",
"uids",
".",
"first",
"(",
"options",
"[",
":count",
"]",
")",
"if",
"options",
"[",
":count",
"]",
".",
"is_a?",
"(",
"Integer",
")",
"uids",
".",
"reverse!",
"if",
"(",
"options",
"[",
":what",
"]",
".",
"to_sym",
"==",
":last",
"&&",
"options",
"[",
":order",
"]",
".",
"to_sym",
"==",
":asc",
")",
"||",
"(",
"options",
"[",
":what",
"]",
".",
"to_sym",
"!=",
":last",
"&&",
"options",
"[",
":order",
"]",
".",
"to_sym",
"==",
":desc",
")",
"if",
"block_given?",
"uids",
".",
"each",
"do",
"|",
"uid",
"|",
"uid",
"=",
"options",
"[",
":uid",
"]",
".",
"to_i",
"unless",
"options",
"[",
":uid",
"]",
".",
"nil?",
"fetchdata",
"=",
"imap",
".",
"uid_fetch",
"(",
"uid",
",",
"[",
"'RFC822'",
",",
"'FLAGS'",
"]",
")",
"[",
"0",
"]",
"new_message",
"=",
"Mail",
".",
"new",
"(",
"fetchdata",
".",
"attr",
"[",
"'RFC822'",
"]",
")",
"new_message",
".",
"mark_for_delete",
"=",
"true",
"if",
"options",
"[",
":delete_after_find",
"]",
"if",
"block",
".",
"arity",
"==",
"4",
"yield",
"new_message",
",",
"imap",
",",
"uid",
",",
"fetchdata",
".",
"attr",
"[",
"'FLAGS'",
"]",
"elsif",
"block",
".",
"arity",
"==",
"3",
"yield",
"new_message",
",",
"imap",
",",
"uid",
"else",
"yield",
"new_message",
"end",
"imap",
".",
"uid_store",
"(",
"uid",
",",
"\"+FLAGS\"",
",",
"[",
"Net",
"::",
"IMAP",
"::",
"DELETED",
"]",
")",
"if",
"options",
"[",
":delete_after_find",
"]",
"&&",
"new_message",
".",
"is_marked_for_delete?",
"break",
"unless",
"options",
"[",
":uid",
"]",
".",
"nil?",
"end",
"imap",
".",
"expunge",
"if",
"options",
"[",
":delete_after_find",
"]",
"else",
"emails",
"=",
"[",
"]",
"uids",
".",
"each",
"do",
"|",
"uid",
"|",
"uid",
"=",
"options",
"[",
":uid",
"]",
".",
"to_i",
"unless",
"options",
"[",
":uid",
"]",
".",
"nil?",
"fetchdata",
"=",
"imap",
".",
"uid_fetch",
"(",
"uid",
",",
"[",
"'RFC822'",
"]",
")",
"[",
"0",
"]",
"emails",
"<<",
"Mail",
".",
"new",
"(",
"fetchdata",
".",
"attr",
"[",
"'RFC822'",
"]",
")",
"imap",
".",
"uid_store",
"(",
"uid",
",",
"\"+FLAGS\"",
",",
"[",
"Net",
"::",
"IMAP",
"::",
"DELETED",
"]",
")",
"if",
"options",
"[",
":delete_after_find",
"]",
"break",
"unless",
"options",
"[",
":uid",
"]",
".",
"nil?",
"end",
"imap",
".",
"expunge",
"if",
"options",
"[",
":delete_after_find",
"]",
"emails",
".",
"size",
"==",
"1",
"&&",
"options",
"[",
":count",
"]",
"==",
"1",
"?",
"emails",
".",
"first",
":",
"emails",
"end",
"end",
"end"
] | Find emails in a IMAP mailbox. Without any options, the 10 last received emails are returned.
Possible options:
mailbox: mailbox to search the email(s) in. The default is 'INBOX'.
what: last or first emails. The default is :first.
order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
count: number of emails to retrieve. The default value is 10. A value of 1 returns an
instance of Message, not an array of Message instances.
read_only: will ensure that no writes are made to the inbox during the session. Specifically, if this is
set to true, the code will use the EXAMINE command to retrieve the mail. If set to false, which
is the default, a SELECT command will be used to retrieve the mail
This is helpful when you don't want your messages to be set to read automatically. Default is false.
delete_after_find: flag for whether to delete each retreived email after find. Default
is false. Use #find_and_delete if you would like this to default to true.
keys: are passed as criteria to the SEARCH command. They can either be a string holding the entire search string,
or a single-dimension array of search keywords and arguments. Refer to [IMAP] section 6.4.4 for a full list
The default is 'ALL'
search_charset: charset to pass to IMAP server search. Omitted by default. Example: 'UTF-8' or 'ASCII'. | [
"Find",
"emails",
"in",
"a",
"IMAP",
"mailbox",
".",
"Without",
"any",
"options",
"the",
"10",
"last",
"received",
"emails",
"are",
"returned",
"."
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/network/retriever_methods/imap.rb#L73-L116 | train |
mikel/mail | lib/mail/network/retriever_methods/imap.rb | Mail.IMAP.delete_all | def delete_all(mailbox='INBOX')
mailbox ||= 'INBOX'
mailbox = Net::IMAP.encode_utf7(mailbox)
start do |imap|
imap.select(mailbox)
imap.uid_search(['ALL']).each do |uid|
imap.uid_store(uid, "+FLAGS", [Net::IMAP::DELETED])
end
imap.expunge
end
end | ruby | def delete_all(mailbox='INBOX')
mailbox ||= 'INBOX'
mailbox = Net::IMAP.encode_utf7(mailbox)
start do |imap|
imap.select(mailbox)
imap.uid_search(['ALL']).each do |uid|
imap.uid_store(uid, "+FLAGS", [Net::IMAP::DELETED])
end
imap.expunge
end
end | [
"def",
"delete_all",
"(",
"mailbox",
"=",
"'INBOX'",
")",
"mailbox",
"||=",
"'INBOX'",
"mailbox",
"=",
"Net",
"::",
"IMAP",
".",
"encode_utf7",
"(",
"mailbox",
")",
"start",
"do",
"|",
"imap",
"|",
"imap",
".",
"select",
"(",
"mailbox",
")",
"imap",
".",
"uid_search",
"(",
"[",
"'ALL'",
"]",
")",
".",
"each",
"do",
"|",
"uid",
"|",
"imap",
".",
"uid_store",
"(",
"uid",
",",
"\"+FLAGS\"",
",",
"[",
"Net",
"::",
"IMAP",
"::",
"DELETED",
"]",
")",
"end",
"imap",
".",
"expunge",
"end",
"end"
] | Delete all emails from a IMAP mailbox | [
"Delete",
"all",
"emails",
"from",
"a",
"IMAP",
"mailbox"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/network/retriever_methods/imap.rb#L119-L130 | train |
mikel/mail | lib/mail/network/retriever_methods/imap.rb | Mail.IMAP.start | def start(config=Mail::Configuration.instance, &block)
raise ArgumentError.new("Mail::Retrievable#imap_start takes a block") unless block_given?
if settings[:enable_starttls] && settings[:enable_ssl]
raise ArgumentError, ":enable_starttls and :enable_ssl are mutually exclusive. Set :enable_ssl if you're on an IMAPS connection. Set :enable_starttls if you're on an IMAP connection and using STARTTLS for secure TLS upgrade."
end
imap = Net::IMAP.new(settings[:address], settings[:port], settings[:enable_ssl], nil, false)
imap.starttls if settings[:enable_starttls]
if settings[:authentication].nil?
imap.login(settings[:user_name], settings[:password])
else
# Note that Net::IMAP#authenticate('LOGIN', ...) is not equal with Net::IMAP#login(...)!
# (see also http://www.ensta.fr/~diam/ruby/online/ruby-doc-stdlib/libdoc/net/imap/rdoc/classes/Net/IMAP.html#M000718)
imap.authenticate(settings[:authentication], settings[:user_name], settings[:password])
end
yield imap
ensure
if defined?(imap) && imap && !imap.disconnected?
imap.disconnect
end
end | ruby | def start(config=Mail::Configuration.instance, &block)
raise ArgumentError.new("Mail::Retrievable#imap_start takes a block") unless block_given?
if settings[:enable_starttls] && settings[:enable_ssl]
raise ArgumentError, ":enable_starttls and :enable_ssl are mutually exclusive. Set :enable_ssl if you're on an IMAPS connection. Set :enable_starttls if you're on an IMAP connection and using STARTTLS for secure TLS upgrade."
end
imap = Net::IMAP.new(settings[:address], settings[:port], settings[:enable_ssl], nil, false)
imap.starttls if settings[:enable_starttls]
if settings[:authentication].nil?
imap.login(settings[:user_name], settings[:password])
else
# Note that Net::IMAP#authenticate('LOGIN', ...) is not equal with Net::IMAP#login(...)!
# (see also http://www.ensta.fr/~diam/ruby/online/ruby-doc-stdlib/libdoc/net/imap/rdoc/classes/Net/IMAP.html#M000718)
imap.authenticate(settings[:authentication], settings[:user_name], settings[:password])
end
yield imap
ensure
if defined?(imap) && imap && !imap.disconnected?
imap.disconnect
end
end | [
"def",
"start",
"(",
"config",
"=",
"Mail",
"::",
"Configuration",
".",
"instance",
",",
"&",
"block",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Mail::Retrievable#imap_start takes a block\"",
")",
"unless",
"block_given?",
"if",
"settings",
"[",
":enable_starttls",
"]",
"&&",
"settings",
"[",
":enable_ssl",
"]",
"raise",
"ArgumentError",
",",
"\":enable_starttls and :enable_ssl are mutually exclusive. Set :enable_ssl if you're on an IMAPS connection. Set :enable_starttls if you're on an IMAP connection and using STARTTLS for secure TLS upgrade.\"",
"end",
"imap",
"=",
"Net",
"::",
"IMAP",
".",
"new",
"(",
"settings",
"[",
":address",
"]",
",",
"settings",
"[",
":port",
"]",
",",
"settings",
"[",
":enable_ssl",
"]",
",",
"nil",
",",
"false",
")",
"imap",
".",
"starttls",
"if",
"settings",
"[",
":enable_starttls",
"]",
"if",
"settings",
"[",
":authentication",
"]",
".",
"nil?",
"imap",
".",
"login",
"(",
"settings",
"[",
":user_name",
"]",
",",
"settings",
"[",
":password",
"]",
")",
"else",
"# Note that Net::IMAP#authenticate('LOGIN', ...) is not equal with Net::IMAP#login(...)!",
"# (see also http://www.ensta.fr/~diam/ruby/online/ruby-doc-stdlib/libdoc/net/imap/rdoc/classes/Net/IMAP.html#M000718)",
"imap",
".",
"authenticate",
"(",
"settings",
"[",
":authentication",
"]",
",",
"settings",
"[",
":user_name",
"]",
",",
"settings",
"[",
":password",
"]",
")",
"end",
"yield",
"imap",
"ensure",
"if",
"defined?",
"(",
"imap",
")",
"&&",
"imap",
"&&",
"!",
"imap",
".",
"disconnected?",
"imap",
".",
"disconnect",
"end",
"end"
] | Start an IMAP session and ensures that it will be closed in any case. | [
"Start",
"an",
"IMAP",
"session",
"and",
"ensures",
"that",
"it",
"will",
"be",
"closed",
"in",
"any",
"case",
"."
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/network/retriever_methods/imap.rb#L160-L184 | train |
mikel/mail | lib/mail/header.rb | Mail.Header.fields= | def fields=(unfolded_fields)
@fields = Mail::FieldList.new
if unfolded_fields.size > self.class.maximum_amount
Kernel.warn "WARNING: More than #{self.class.maximum_amount} header fields; only using the first #{self.class.maximum_amount} and ignoring the rest"
unfolded_fields = unfolded_fields.slice(0...self.class.maximum_amount)
end
unfolded_fields.each do |field|
if field = Field.parse(field, charset)
@fields.add_field field
end
end
end | ruby | def fields=(unfolded_fields)
@fields = Mail::FieldList.new
if unfolded_fields.size > self.class.maximum_amount
Kernel.warn "WARNING: More than #{self.class.maximum_amount} header fields; only using the first #{self.class.maximum_amount} and ignoring the rest"
unfolded_fields = unfolded_fields.slice(0...self.class.maximum_amount)
end
unfolded_fields.each do |field|
if field = Field.parse(field, charset)
@fields.add_field field
end
end
end | [
"def",
"fields",
"=",
"(",
"unfolded_fields",
")",
"@fields",
"=",
"Mail",
"::",
"FieldList",
".",
"new",
"if",
"unfolded_fields",
".",
"size",
">",
"self",
".",
"class",
".",
"maximum_amount",
"Kernel",
".",
"warn",
"\"WARNING: More than #{self.class.maximum_amount} header fields; only using the first #{self.class.maximum_amount} and ignoring the rest\"",
"unfolded_fields",
"=",
"unfolded_fields",
".",
"slice",
"(",
"0",
"...",
"self",
".",
"class",
".",
"maximum_amount",
")",
"end",
"unfolded_fields",
".",
"each",
"do",
"|",
"field",
"|",
"if",
"field",
"=",
"Field",
".",
"parse",
"(",
"field",
",",
"charset",
")",
"@fields",
".",
"add_field",
"field",
"end",
"end",
"end"
] | 3.6. Field definitions
It is important to note that the header fields are not guaranteed to
be in a particular order. They may appear in any order, and they
have been known to be reordered occasionally when transported over
the Internet. However, for the purposes of this standard, header
fields SHOULD NOT be reordered when a message is transported or
transformed. More importantly, the trace header fields and resent
header fields MUST NOT be reordered, and SHOULD be kept in blocks
prepended to the message. See sections 3.6.6 and 3.6.7 for more
information.
Populates the fields container with Field objects in the order it
receives them in.
Acceps an array of field string values, for example:
h = Header.new
h.fields = ['From: [email protected]', 'To: [email protected]'] | [
"3",
".",
"6",
".",
"Field",
"definitions"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/header.rb#L90-L103 | train |
mikel/mail | lib/mail/header.rb | Mail.Header.[]= | def []=(name, value)
name = name.to_s
if name.include?(Constants::COLON)
raise ArgumentError, "Header names may not contain a colon: #{name.inspect}"
end
name = Utilities.dasherize(name)
# Assign nil to delete the field
if value.nil?
fields.delete_field name
else
fields.add_field Field.new(name.to_s, value, charset)
# Update charset if specified in Content-Type
if name == 'content-type'
params = self[:content_type].parameters rescue nil
@charset = params[:charset] if params && params[:charset]
end
end
end | ruby | def []=(name, value)
name = name.to_s
if name.include?(Constants::COLON)
raise ArgumentError, "Header names may not contain a colon: #{name.inspect}"
end
name = Utilities.dasherize(name)
# Assign nil to delete the field
if value.nil?
fields.delete_field name
else
fields.add_field Field.new(name.to_s, value, charset)
# Update charset if specified in Content-Type
if name == 'content-type'
params = self[:content_type].parameters rescue nil
@charset = params[:charset] if params && params[:charset]
end
end
end | [
"def",
"[]=",
"(",
"name",
",",
"value",
")",
"name",
"=",
"name",
".",
"to_s",
"if",
"name",
".",
"include?",
"(",
"Constants",
"::",
"COLON",
")",
"raise",
"ArgumentError",
",",
"\"Header names may not contain a colon: #{name.inspect}\"",
"end",
"name",
"=",
"Utilities",
".",
"dasherize",
"(",
"name",
")",
"# Assign nil to delete the field",
"if",
"value",
".",
"nil?",
"fields",
".",
"delete_field",
"name",
"else",
"fields",
".",
"add_field",
"Field",
".",
"new",
"(",
"name",
".",
"to_s",
",",
"value",
",",
"charset",
")",
"# Update charset if specified in Content-Type",
"if",
"name",
"==",
"'content-type'",
"params",
"=",
"self",
"[",
":content_type",
"]",
".",
"parameters",
"rescue",
"nil",
"@charset",
"=",
"params",
"[",
":charset",
"]",
"if",
"params",
"&&",
"params",
"[",
":charset",
"]",
"end",
"end",
"end"
] | Sets the FIRST matching field in the header to passed value, or deletes
the FIRST field matched from the header if passed nil
Example:
h = Header.new
h.fields = ['To: [email protected]', 'X-Mail-SPAM: 15', 'X-Mail-SPAM: 20']
h['To'] = '[email protected]'
h['To'] #=> '[email protected]'
h['X-Mail-SPAM'] = '10000'
h['X-Mail-SPAM'] # => ['15', '20', '10000']
h['X-Mail-SPAM'] = nil
h['X-Mail-SPAM'] # => nil | [
"Sets",
"the",
"FIRST",
"matching",
"field",
"in",
"the",
"header",
"to",
"passed",
"value",
"or",
"deletes",
"the",
"FIRST",
"field",
"matched",
"from",
"the",
"header",
"if",
"passed",
"nil"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/header.rb#L147-L167 | train |
mikel/mail | lib/mail/message.rb | Mail.Message.default | def default( sym, val = nil )
if val
header[sym] = val
elsif field = header[sym]
field.default
end
end | ruby | def default( sym, val = nil )
if val
header[sym] = val
elsif field = header[sym]
field.default
end
end | [
"def",
"default",
"(",
"sym",
",",
"val",
"=",
"nil",
")",
"if",
"val",
"header",
"[",
"sym",
"]",
"=",
"val",
"elsif",
"field",
"=",
"header",
"[",
"sym",
"]",
"field",
".",
"default",
"end",
"end"
] | Returns the default value of the field requested as a symbol.
Each header field has a :default method which returns the most common use case for
that field, for example, the date field types will return a DateTime object when
sent :default, the subject, or unstructured fields will return a decoded string of
their value, the address field types will return a single addr_spec or an array of
addr_specs if there is more than one. | [
"Returns",
"the",
"default",
"value",
"of",
"the",
"field",
"requested",
"as",
"a",
"symbol",
"."
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/message.rb#L1204-L1210 | train |
mikel/mail | lib/mail/message.rb | Mail.Message.[]= | def []=(name, value)
if name.to_s == 'body'
self.body = value
elsif name.to_s =~ /content[-_]type/i
header[name] = value
elsif name.to_s == 'charset'
self.charset = value
else
header[name] = value
end
end | ruby | def []=(name, value)
if name.to_s == 'body'
self.body = value
elsif name.to_s =~ /content[-_]type/i
header[name] = value
elsif name.to_s == 'charset'
self.charset = value
else
header[name] = value
end
end | [
"def",
"[]=",
"(",
"name",
",",
"value",
")",
"if",
"name",
".",
"to_s",
"==",
"'body'",
"self",
".",
"body",
"=",
"value",
"elsif",
"name",
".",
"to_s",
"=~",
"/",
"/i",
"header",
"[",
"name",
"]",
"=",
"value",
"elsif",
"name",
".",
"to_s",
"==",
"'charset'",
"self",
".",
"charset",
"=",
"value",
"else",
"header",
"[",
"name",
"]",
"=",
"value",
"end",
"end"
] | Allows you to add an arbitrary header
Example:
mail['foo'] = '1234'
mail['foo'].to_s #=> '1234' | [
"Allows",
"you",
"to",
"add",
"an",
"arbitrary",
"header"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/message.rb#L1316-L1326 | train |
mikel/mail | lib/mail/message.rb | Mail.Message.method_missing | def method_missing(name, *args, &block)
#:nodoc:
# Only take the structured fields, as we could take _anything_ really
# as it could become an optional field... "but therin lies the dark side"
field_name = Utilities.underscoreize(name).chomp("=")
if Mail::Field::KNOWN_FIELDS.include?(field_name)
if args.empty?
header[field_name]
else
header[field_name] = args.first
end
else
super # otherwise pass it on
end
#:startdoc:
end | ruby | def method_missing(name, *args, &block)
#:nodoc:
# Only take the structured fields, as we could take _anything_ really
# as it could become an optional field... "but therin lies the dark side"
field_name = Utilities.underscoreize(name).chomp("=")
if Mail::Field::KNOWN_FIELDS.include?(field_name)
if args.empty?
header[field_name]
else
header[field_name] = args.first
end
else
super # otherwise pass it on
end
#:startdoc:
end | [
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"#:nodoc:",
"# Only take the structured fields, as we could take _anything_ really",
"# as it could become an optional field... \"but therin lies the dark side\"",
"field_name",
"=",
"Utilities",
".",
"underscoreize",
"(",
"name",
")",
".",
"chomp",
"(",
"\"=\"",
")",
"if",
"Mail",
"::",
"Field",
"::",
"KNOWN_FIELDS",
".",
"include?",
"(",
"field_name",
")",
"if",
"args",
".",
"empty?",
"header",
"[",
"field_name",
"]",
"else",
"header",
"[",
"field_name",
"]",
"=",
"args",
".",
"first",
"end",
"else",
"super",
"# otherwise pass it on",
"end",
"#:startdoc:",
"end"
] | Method Missing in this implementation allows you to set any of the
standard fields directly as you would the "to", "subject" etc.
Those fields used most often (to, subject et al) are given their
own method for ease of documentation and also to avoid the hook
call to method missing.
This will only catch the known fields listed in:
Mail::Field::KNOWN_FIELDS
as per RFC 2822, any ruby string or method name could pretty much
be a field name, so we don't want to just catch ANYTHING sent to
a message object and interpret it as a header.
This method provides all three types of header call to set, read
and explicitly set with the = operator
Examples:
mail.comments = 'These are some comments'
mail.comments #=> 'These are some comments'
mail.comments 'These are other comments'
mail.comments #=> 'These are other comments'
mail.date = 'Tue, 1 Jul 2003 10:52:37 +0200'
mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'
mail.date 'Tue, 1 Jul 2003 10:52:37 +0200'
mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'
mail.resent_msg_id = '<1234@resent_msg_id.lindsaar.net>'
mail.resent_msg_id #=> '<1234@resent_msg_id.lindsaar.net>'
mail.resent_msg_id '<4567@resent_msg_id.lindsaar.net>'
mail.resent_msg_id #=> '<4567@resent_msg_id.lindsaar.net>' | [
"Method",
"Missing",
"in",
"this",
"implementation",
"allows",
"you",
"to",
"set",
"any",
"of",
"the",
"standard",
"fields",
"directly",
"as",
"you",
"would",
"the",
"to",
"subject",
"etc",
"."
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/message.rb#L1377-L1392 | train |
mikel/mail | lib/mail/message.rb | Mail.Message.add_charset | def add_charset
if !body.empty?
# Only give a warning if this isn't an attachment, has non US-ASCII and the user
# has not specified an encoding explicitly.
if @defaulted_charset && !body.raw_source.ascii_only? && !self.attachment?
warning = "Non US-ASCII detected and no charset defined.\nDefaulting to UTF-8, set your own if this is incorrect.\n"
warn(warning)
end
header[:content_type].parameters['charset'] = @charset
end
end | ruby | def add_charset
if !body.empty?
# Only give a warning if this isn't an attachment, has non US-ASCII and the user
# has not specified an encoding explicitly.
if @defaulted_charset && !body.raw_source.ascii_only? && !self.attachment?
warning = "Non US-ASCII detected and no charset defined.\nDefaulting to UTF-8, set your own if this is incorrect.\n"
warn(warning)
end
header[:content_type].parameters['charset'] = @charset
end
end | [
"def",
"add_charset",
"if",
"!",
"body",
".",
"empty?",
"# Only give a warning if this isn't an attachment, has non US-ASCII and the user",
"# has not specified an encoding explicitly.",
"if",
"@defaulted_charset",
"&&",
"!",
"body",
".",
"raw_source",
".",
"ascii_only?",
"&&",
"!",
"self",
".",
"attachment?",
"warning",
"=",
"\"Non US-ASCII detected and no charset defined.\\nDefaulting to UTF-8, set your own if this is incorrect.\\n\"",
"warn",
"(",
"warning",
")",
"end",
"header",
"[",
":content_type",
"]",
".",
"parameters",
"[",
"'charset'",
"]",
"=",
"@charset",
"end",
"end"
] | Adds a content type and charset if the body is US-ASCII
Otherwise raises a warning | [
"Adds",
"a",
"content",
"type",
"and",
"charset",
"if",
"the",
"body",
"is",
"US",
"-",
"ASCII"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/message.rb#L1472-L1482 | train |
mikel/mail | lib/mail/message.rb | Mail.Message.add_part | def add_part(part)
if !body.multipart? && !Utilities.blank?(self.body.decoded)
@text_part = Mail::Part.new('Content-Type: text/plain;')
@text_part.body = body.decoded
self.body << @text_part
add_multipart_alternate_header
end
add_boundary
self.body << part
end | ruby | def add_part(part)
if !body.multipart? && !Utilities.blank?(self.body.decoded)
@text_part = Mail::Part.new('Content-Type: text/plain;')
@text_part.body = body.decoded
self.body << @text_part
add_multipart_alternate_header
end
add_boundary
self.body << part
end | [
"def",
"add_part",
"(",
"part",
")",
"if",
"!",
"body",
".",
"multipart?",
"&&",
"!",
"Utilities",
".",
"blank?",
"(",
"self",
".",
"body",
".",
"decoded",
")",
"@text_part",
"=",
"Mail",
"::",
"Part",
".",
"new",
"(",
"'Content-Type: text/plain;'",
")",
"@text_part",
".",
"body",
"=",
"body",
".",
"decoded",
"self",
".",
"body",
"<<",
"@text_part",
"add_multipart_alternate_header",
"end",
"add_boundary",
"self",
".",
"body",
"<<",
"part",
"end"
] | Adds a part to the parts list or creates the part list | [
"Adds",
"a",
"part",
"to",
"the",
"parts",
"list",
"or",
"creates",
"the",
"part",
"list"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/message.rb#L1699-L1708 | train |
mikel/mail | lib/mail/message.rb | Mail.Message.part | def part(params = {})
new_part = Part.new(params)
yield new_part if block_given?
add_part(new_part)
end | ruby | def part(params = {})
new_part = Part.new(params)
yield new_part if block_given?
add_part(new_part)
end | [
"def",
"part",
"(",
"params",
"=",
"{",
"}",
")",
"new_part",
"=",
"Part",
".",
"new",
"(",
"params",
")",
"yield",
"new_part",
"if",
"block_given?",
"add_part",
"(",
"new_part",
")",
"end"
] | Allows you to add a part in block form to an existing mail message object
Example:
mail = Mail.new do
part :content_type => "multipart/alternative", :content_disposition => "inline" do |p|
p.part :content_type => "text/plain", :body => "test text\nline #2"
p.part :content_type => "text/html", :body => "<b>test</b> HTML<br/>\nline #2"
end
end | [
"Allows",
"you",
"to",
"add",
"a",
"part",
"in",
"block",
"form",
"to",
"an",
"existing",
"mail",
"message",
"object"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/message.rb#L1720-L1724 | train |
mikel/mail | lib/mail/message.rb | Mail.Message.add_file | def add_file(values)
convert_to_multipart unless self.multipart? || Utilities.blank?(self.body.decoded)
add_multipart_mixed_header
if values.is_a?(String)
basename = File.basename(values)
filedata = File.open(values, 'rb') { |f| f.read }
else
basename = values[:filename]
filedata = values
end
self.attachments[basename] = filedata
end | ruby | def add_file(values)
convert_to_multipart unless self.multipart? || Utilities.blank?(self.body.decoded)
add_multipart_mixed_header
if values.is_a?(String)
basename = File.basename(values)
filedata = File.open(values, 'rb') { |f| f.read }
else
basename = values[:filename]
filedata = values
end
self.attachments[basename] = filedata
end | [
"def",
"add_file",
"(",
"values",
")",
"convert_to_multipart",
"unless",
"self",
".",
"multipart?",
"||",
"Utilities",
".",
"blank?",
"(",
"self",
".",
"body",
".",
"decoded",
")",
"add_multipart_mixed_header",
"if",
"values",
".",
"is_a?",
"(",
"String",
")",
"basename",
"=",
"File",
".",
"basename",
"(",
"values",
")",
"filedata",
"=",
"File",
".",
"open",
"(",
"values",
",",
"'rb'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"read",
"}",
"else",
"basename",
"=",
"values",
"[",
":filename",
"]",
"filedata",
"=",
"values",
"end",
"self",
".",
"attachments",
"[",
"basename",
"]",
"=",
"filedata",
"end"
] | Adds a file to the message. You have two options with this method, you can
just pass in the absolute path to the file you want and Mail will read the file,
get the filename from the path you pass in and guess the MIME media type, or you
can pass in the filename as a string, and pass in the file content as a blob.
Example:
m = Mail.new
m.add_file('/path/to/filename.png')
m = Mail.new
m.add_file(:filename => 'filename.png', :content => File.read('/path/to/file.jpg'))
Note also that if you add a file to an existing message, Mail will convert that message
to a MIME multipart email, moving whatever plain text body you had into its own text
plain part.
Example:
m = Mail.new do
body 'this is some text'
end
m.multipart? #=> false
m.add_file('/path/to/filename.png')
m.multipart? #=> true
m.parts.first.content_type.content_type #=> 'text/plain'
m.parts.last.content_type.content_type #=> 'image/png'
See also #attachments | [
"Adds",
"a",
"file",
"to",
"the",
"message",
".",
"You",
"have",
"two",
"options",
"with",
"this",
"method",
"you",
"can",
"just",
"pass",
"in",
"the",
"absolute",
"path",
"to",
"the",
"file",
"you",
"want",
"and",
"Mail",
"will",
"read",
"the",
"file",
"get",
"the",
"filename",
"from",
"the",
"path",
"you",
"pass",
"in",
"and",
"guess",
"the",
"MIME",
"media",
"type",
"or",
"you",
"can",
"pass",
"in",
"the",
"filename",
"as",
"a",
"string",
"and",
"pass",
"in",
"the",
"file",
"content",
"as",
"a",
"blob",
"."
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/message.rb#L1755-L1766 | train |
mikel/mail | lib/mail/message.rb | Mail.Message.ready_to_send! | def ready_to_send!
identify_and_set_transfer_encoding
parts.each do |part|
part.transport_encoding = transport_encoding
part.ready_to_send!
end
add_required_fields
end | ruby | def ready_to_send!
identify_and_set_transfer_encoding
parts.each do |part|
part.transport_encoding = transport_encoding
part.ready_to_send!
end
add_required_fields
end | [
"def",
"ready_to_send!",
"identify_and_set_transfer_encoding",
"parts",
".",
"each",
"do",
"|",
"part",
"|",
"part",
".",
"transport_encoding",
"=",
"transport_encoding",
"part",
".",
"ready_to_send!",
"end",
"add_required_fields",
"end"
] | Encodes the message, calls encode on all its parts, gets an email message
ready to send | [
"Encodes",
"the",
"message",
"calls",
"encode",
"on",
"all",
"its",
"parts",
"gets",
"an",
"email",
"message",
"ready",
"to",
"send"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/message.rb#L1789-L1796 | train |
mikel/mail | lib/mail/message.rb | Mail.Message.encoded | def encoded
ready_to_send!
buffer = header.encoded
buffer << "\r\n"
buffer << body.encoded(content_transfer_encoding)
buffer
end | ruby | def encoded
ready_to_send!
buffer = header.encoded
buffer << "\r\n"
buffer << body.encoded(content_transfer_encoding)
buffer
end | [
"def",
"encoded",
"ready_to_send!",
"buffer",
"=",
"header",
".",
"encoded",
"buffer",
"<<",
"\"\\r\\n\"",
"buffer",
"<<",
"body",
".",
"encoded",
"(",
"content_transfer_encoding",
")",
"buffer",
"end"
] | Outputs an encoded string representation of the mail message including
all headers, attachments, etc. This is an encoded email in US-ASCII,
so it is able to be directly sent to an email server. | [
"Outputs",
"an",
"encoded",
"string",
"representation",
"of",
"the",
"mail",
"message",
"including",
"all",
"headers",
"attachments",
"etc",
".",
"This",
"is",
"an",
"encoded",
"email",
"in",
"US",
"-",
"ASCII",
"so",
"it",
"is",
"able",
"to",
"be",
"directly",
"sent",
"to",
"an",
"email",
"server",
"."
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/message.rb#L1801-L1807 | train |
mikel/mail | lib/mail/message.rb | Mail.Message.body_lazy | def body_lazy(value)
process_body_raw if @body_raw && value
case
when value == nil || value.length<=0
@body = Mail::Body.new('')
@body_raw = nil
add_encoding_to_body
when @body && @body.multipart?
self.text_part = value
else
@body_raw = value
end
end | ruby | def body_lazy(value)
process_body_raw if @body_raw && value
case
when value == nil || value.length<=0
@body = Mail::Body.new('')
@body_raw = nil
add_encoding_to_body
when @body && @body.multipart?
self.text_part = value
else
@body_raw = value
end
end | [
"def",
"body_lazy",
"(",
"value",
")",
"process_body_raw",
"if",
"@body_raw",
"&&",
"value",
"case",
"when",
"value",
"==",
"nil",
"||",
"value",
".",
"length",
"<=",
"0",
"@body",
"=",
"Mail",
"::",
"Body",
".",
"new",
"(",
"''",
")",
"@body_raw",
"=",
"nil",
"add_encoding_to_body",
"when",
"@body",
"&&",
"@body",
".",
"multipart?",
"self",
".",
"text_part",
"=",
"value",
"else",
"@body_raw",
"=",
"value",
"end",
"end"
] | see comments to body=. We take data and process it lazily | [
"see",
"comments",
"to",
"body",
"=",
".",
"We",
"take",
"data",
"and",
"process",
"it",
"lazily"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/message.rb#L1988-L2000 | train |
mikel/mail | lib/mail/elements/address.rb | Mail.Address.comments | def comments
parse unless @parsed
comments = get_comments
if comments.nil? || comments.none?
nil
else
comments.map { |c| c.squeeze(Constants::SPACE) }
end
end | ruby | def comments
parse unless @parsed
comments = get_comments
if comments.nil? || comments.none?
nil
else
comments.map { |c| c.squeeze(Constants::SPACE) }
end
end | [
"def",
"comments",
"parse",
"unless",
"@parsed",
"comments",
"=",
"get_comments",
"if",
"comments",
".",
"nil?",
"||",
"comments",
".",
"none?",
"nil",
"else",
"comments",
".",
"map",
"{",
"|",
"c",
"|",
"c",
".",
"squeeze",
"(",
"Constants",
"::",
"SPACE",
")",
"}",
"end",
"end"
] | Returns an array of comments that are in the email, or nil if there
are no comments
a = Address.new('Mikel Lindsaar (My email address) <[email protected]>')
a.comments #=> ['My email address']
b = Address.new('Mikel Lindsaar <[email protected]>')
b.comments #=> nil | [
"Returns",
"an",
"array",
"of",
"comments",
"that",
"are",
"in",
"the",
"email",
"or",
"nil",
"if",
"there",
"are",
"no",
"comments"
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/elements/address.rb#L132-L140 | train |
mikel/mail | lib/mail/network/retriever_methods/base.rb | Mail.Retriever.all | def all(options = nil, &block)
options = options ? Hash[options] : {}
options[:count] = :all
find(options, &block)
end | ruby | def all(options = nil, &block)
options = options ? Hash[options] : {}
options[:count] = :all
find(options, &block)
end | [
"def",
"all",
"(",
"options",
"=",
"nil",
",",
"&",
"block",
")",
"options",
"=",
"options",
"?",
"Hash",
"[",
"options",
"]",
":",
"{",
"}",
"options",
"[",
":count",
"]",
"=",
":all",
"find",
"(",
"options",
",",
"block",
")",
"end"
] | Get all emails.
Possible options:
order: order of emails returned. Possible values are :asc or :desc. Default value is :asc. | [
"Get",
"all",
"emails",
"."
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/network/retriever_methods/base.rb#L39-L43 | train |
mikel/mail | lib/mail/network/retriever_methods/base.rb | Mail.Retriever.find_and_delete | def find_and_delete(options = nil, &block)
options = options ? Hash[options] : {}
options[:delete_after_find] ||= true
find(options, &block)
end | ruby | def find_and_delete(options = nil, &block)
options = options ? Hash[options] : {}
options[:delete_after_find] ||= true
find(options, &block)
end | [
"def",
"find_and_delete",
"(",
"options",
"=",
"nil",
",",
"&",
"block",
")",
"options",
"=",
"options",
"?",
"Hash",
"[",
"options",
"]",
":",
"{",
"}",
"options",
"[",
":delete_after_find",
"]",
"||=",
"true",
"find",
"(",
"options",
",",
"block",
")",
"end"
] | Find emails in the mailbox, and then deletes them. Without any options, the
five last received emails are returned.
Possible options:
what: last or first emails. The default is :first.
order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
count: number of emails to retrieve. The default value is 10. A value of 1 returns an
instance of Message, not an array of Message instances.
delete_after_find: flag for whether to delete each retreived email after find. Default
is true. Call #find if you would like this to default to false. | [
"Find",
"emails",
"in",
"the",
"mailbox",
"and",
"then",
"deletes",
"them",
".",
"Without",
"any",
"options",
"the",
"five",
"last",
"received",
"emails",
"are",
"returned",
"."
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/network/retriever_methods/base.rb#L56-L60 | train |
mikel/mail | lib/mail/field_list.rb | Mail.FieldList.insert_field | def insert_field(field)
lo, hi = 0, size
while lo < hi
mid = (lo + hi).div(2)
if field < self[mid]
hi = mid
else
lo = mid + 1
end
end
insert lo, field
end | ruby | def insert_field(field)
lo, hi = 0, size
while lo < hi
mid = (lo + hi).div(2)
if field < self[mid]
hi = mid
else
lo = mid + 1
end
end
insert lo, field
end | [
"def",
"insert_field",
"(",
"field",
")",
"lo",
",",
"hi",
"=",
"0",
",",
"size",
"while",
"lo",
"<",
"hi",
"mid",
"=",
"(",
"lo",
"+",
"hi",
")",
".",
"div",
"(",
"2",
")",
"if",
"field",
"<",
"self",
"[",
"mid",
"]",
"hi",
"=",
"mid",
"else",
"lo",
"=",
"mid",
"+",
"1",
"end",
"end",
"insert",
"lo",
",",
"field",
"end"
] | Insert the field in sorted order.
Heavily based on bisect.insort from Python, which is:
Copyright (C) 2001-2013 Python Software Foundation.
Licensed under <http://docs.python.org/license.html>
From <http://hg.python.org/cpython/file/2.7/Lib/bisect.py> | [
"Insert",
"the",
"field",
"in",
"sorted",
"order",
"."
] | fb53fb369eb2bf0494ac70675970c90cdcc3f495 | https://github.com/mikel/mail/blob/fb53fb369eb2bf0494ac70675970c90cdcc3f495/lib/mail/field_list.rb#L53-L65 | train |
strongself/Generamba | lib/generamba/template/helpers/catalog_downloader.rb | Generamba.CatalogDownloader.update_all_catalogs_and_return_filepaths | def update_all_catalogs_and_return_filepaths
does_rambafile_exist = Dir[RAMBAFILE_NAME].count > 0
if does_rambafile_exist
rambafile = YAML.load_file(RAMBAFILE_NAME)
catalogs = rambafile[CATALOGS_KEY]
end
terminator = CatalogTerminator.new
terminator.remove_all_catalogs
catalog_paths = [download_catalog(GENERAMBA_CATALOG_NAME, RAMBLER_CATALOG_REPO)]
if catalogs != nil && catalogs.count > 0
catalogs.each do |catalog_url|
catalog_name = catalog_url.split('://').last
catalog_name = catalog_name.gsub('/', '-');
catalog_paths.push(download_catalog(catalog_name, catalog_url))
end
end
return catalog_paths
end | ruby | def update_all_catalogs_and_return_filepaths
does_rambafile_exist = Dir[RAMBAFILE_NAME].count > 0
if does_rambafile_exist
rambafile = YAML.load_file(RAMBAFILE_NAME)
catalogs = rambafile[CATALOGS_KEY]
end
terminator = CatalogTerminator.new
terminator.remove_all_catalogs
catalog_paths = [download_catalog(GENERAMBA_CATALOG_NAME, RAMBLER_CATALOG_REPO)]
if catalogs != nil && catalogs.count > 0
catalogs.each do |catalog_url|
catalog_name = catalog_url.split('://').last
catalog_name = catalog_name.gsub('/', '-');
catalog_paths.push(download_catalog(catalog_name, catalog_url))
end
end
return catalog_paths
end | [
"def",
"update_all_catalogs_and_return_filepaths",
"does_rambafile_exist",
"=",
"Dir",
"[",
"RAMBAFILE_NAME",
"]",
".",
"count",
">",
"0",
"if",
"does_rambafile_exist",
"rambafile",
"=",
"YAML",
".",
"load_file",
"(",
"RAMBAFILE_NAME",
")",
"catalogs",
"=",
"rambafile",
"[",
"CATALOGS_KEY",
"]",
"end",
"terminator",
"=",
"CatalogTerminator",
".",
"new",
"terminator",
".",
"remove_all_catalogs",
"catalog_paths",
"=",
"[",
"download_catalog",
"(",
"GENERAMBA_CATALOG_NAME",
",",
"RAMBLER_CATALOG_REPO",
")",
"]",
"if",
"catalogs",
"!=",
"nil",
"&&",
"catalogs",
".",
"count",
">",
"0",
"catalogs",
".",
"each",
"do",
"|",
"catalog_url",
"|",
"catalog_name",
"=",
"catalog_url",
".",
"split",
"(",
"'://'",
")",
".",
"last",
"catalog_name",
"=",
"catalog_name",
".",
"gsub",
"(",
"'/'",
",",
"'-'",
")",
";",
"catalog_paths",
".",
"push",
"(",
"download_catalog",
"(",
"catalog_name",
",",
"catalog_url",
")",
")",
"end",
"end",
"return",
"catalog_paths",
"end"
] | Updates all of the template catalogs and returns their filepaths.
If there is a Rambafile in the current directory, it also updates all of the catalogs specified there.
@return [Array] An array of filepaths to downloaded catalogs | [
"Updates",
"all",
"of",
"the",
"template",
"catalogs",
"and",
"returns",
"their",
"filepaths",
".",
"If",
"there",
"is",
"a",
"Rambafile",
"in",
"the",
"current",
"directory",
"it",
"also",
"updates",
"all",
"of",
"the",
"catalogs",
"specified",
"there",
"."
] | 9ef343805f3a66f58bc36e120e822d5436a4da97 | https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/helpers/catalog_downloader.rb#L12-L33 | train |
strongself/Generamba | lib/generamba/template/helpers/catalog_downloader.rb | Generamba.CatalogDownloader.download_catalog | def download_catalog(name, url)
catalogs_local_path = Pathname.new(ENV['HOME'])
.join(GENERAMBA_HOME_DIR)
.join(CATALOGS_DIR)
current_catalog_path = catalogs_local_path
.join(name)
if File.exists?(current_catalog_path)
g = Git.open(current_catalog_path)
g.pull
else
Git.clone(url, name, :path => catalogs_local_path)
end
return current_catalog_path
end | ruby | def download_catalog(name, url)
catalogs_local_path = Pathname.new(ENV['HOME'])
.join(GENERAMBA_HOME_DIR)
.join(CATALOGS_DIR)
current_catalog_path = catalogs_local_path
.join(name)
if File.exists?(current_catalog_path)
g = Git.open(current_catalog_path)
g.pull
else
Git.clone(url, name, :path => catalogs_local_path)
end
return current_catalog_path
end | [
"def",
"download_catalog",
"(",
"name",
",",
"url",
")",
"catalogs_local_path",
"=",
"Pathname",
".",
"new",
"(",
"ENV",
"[",
"'HOME'",
"]",
")",
".",
"join",
"(",
"GENERAMBA_HOME_DIR",
")",
".",
"join",
"(",
"CATALOGS_DIR",
")",
"current_catalog_path",
"=",
"catalogs_local_path",
".",
"join",
"(",
"name",
")",
"if",
"File",
".",
"exists?",
"(",
"current_catalog_path",
")",
"g",
"=",
"Git",
".",
"open",
"(",
"current_catalog_path",
")",
"g",
".",
"pull",
"else",
"Git",
".",
"clone",
"(",
"url",
",",
"name",
",",
":path",
"=>",
"catalogs_local_path",
")",
"end",
"return",
"current_catalog_path",
"end"
] | Clones a template catalog from a remote repository
@param name [String] The name of the template catalog
@param url [String] The url of the repository
@return [Pathname] A filepath to the downloaded catalog | [
"Clones",
"a",
"template",
"catalog",
"from",
"a",
"remote",
"repository"
] | 9ef343805f3a66f58bc36e120e822d5436a4da97 | https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/helpers/catalog_downloader.rb#L41-L56 | train |
strongself/Generamba | lib/generamba/template/installer/template_installer_factory.rb | Generamba.TemplateInstallerFactory.installer_for_type | def installer_for_type(type)
case type
when TemplateDeclarationType::LOCAL_TEMPLATE
return Generamba::LocalInstaller.new
when TemplateDeclarationType::REMOTE_TEMPLATE
return Generamba::RemoteInstaller.new
when TemplateDeclarationType::CATALOG_TEMPLATE
return Generamba::CatalogInstaller.new
else
return nil
end
end | ruby | def installer_for_type(type)
case type
when TemplateDeclarationType::LOCAL_TEMPLATE
return Generamba::LocalInstaller.new
when TemplateDeclarationType::REMOTE_TEMPLATE
return Generamba::RemoteInstaller.new
when TemplateDeclarationType::CATALOG_TEMPLATE
return Generamba::CatalogInstaller.new
else
return nil
end
end | [
"def",
"installer_for_type",
"(",
"type",
")",
"case",
"type",
"when",
"TemplateDeclarationType",
"::",
"LOCAL_TEMPLATE",
"return",
"Generamba",
"::",
"LocalInstaller",
".",
"new",
"when",
"TemplateDeclarationType",
"::",
"REMOTE_TEMPLATE",
"return",
"Generamba",
"::",
"RemoteInstaller",
".",
"new",
"when",
"TemplateDeclarationType",
"::",
"CATALOG_TEMPLATE",
"return",
"Generamba",
"::",
"CatalogInstaller",
".",
"new",
"else",
"return",
"nil",
"end",
"end"
] | Provides the appropriate strategy for a given template type | [
"Provides",
"the",
"appropriate",
"strategy",
"for",
"a",
"given",
"template",
"type"
] | 9ef343805f3a66f58bc36e120e822d5436a4da97 | https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/installer/template_installer_factory.rb#L9-L20 | train |
strongself/Generamba | lib/generamba/template/installer/catalog_installer.rb | Generamba.CatalogInstaller.browse_catalog_for_a_template | def browse_catalog_for_a_template(catalog_path, template_name)
template_path = catalog_path.join(template_name)
if Dir.exist?(template_path)
return template_path
end
return nil
end | ruby | def browse_catalog_for_a_template(catalog_path, template_name)
template_path = catalog_path.join(template_name)
if Dir.exist?(template_path)
return template_path
end
return nil
end | [
"def",
"browse_catalog_for_a_template",
"(",
"catalog_path",
",",
"template_name",
")",
"template_path",
"=",
"catalog_path",
".",
"join",
"(",
"template_name",
")",
"if",
"Dir",
".",
"exist?",
"(",
"template_path",
")",
"return",
"template_path",
"end",
"return",
"nil",
"end"
] | Browses a given catalog and returns a template path
@param catalog_path [Pathname] A path to a catalog
@param template_name [String] A name of the template
@return [Pathname] A path to a template, if found | [
"Browses",
"a",
"given",
"catalog",
"and",
"returns",
"a",
"template",
"path"
] | 9ef343805f3a66f58bc36e120e822d5436a4da97 | https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/installer/catalog_installer.rb#L63-L71 | train |
strongself/Generamba | lib/generamba/template/processor/template_processor.rb | Generamba.TemplateProcessor.install_templates | def install_templates(rambafile)
# We always clear previously installed templates to avoid conflicts in different versions
clear_installed_templates
templates = rambafile[TEMPLATES_KEY]
if !templates || templates.count == 0
puts 'You must specify at least one template in Rambafile under the key *templates*'.red
return
end
# Mapping hashes to model objects
templates = rambafile[TEMPLATES_KEY].map { |template_hash|
Generamba::TemplateDeclaration.new(template_hash)
}
catalogs = rambafile[CATALOGS_KEY]
# If there is at least one template from catalogs, we should update our local copy of the catalog
update_catalogs_if_needed(catalogs, templates)
templates.each do |template_declaration|
strategy = @installer_factory.installer_for_type(template_declaration.type)
template_declaration.install(strategy)
end
end | ruby | def install_templates(rambafile)
# We always clear previously installed templates to avoid conflicts in different versions
clear_installed_templates
templates = rambafile[TEMPLATES_KEY]
if !templates || templates.count == 0
puts 'You must specify at least one template in Rambafile under the key *templates*'.red
return
end
# Mapping hashes to model objects
templates = rambafile[TEMPLATES_KEY].map { |template_hash|
Generamba::TemplateDeclaration.new(template_hash)
}
catalogs = rambafile[CATALOGS_KEY]
# If there is at least one template from catalogs, we should update our local copy of the catalog
update_catalogs_if_needed(catalogs, templates)
templates.each do |template_declaration|
strategy = @installer_factory.installer_for_type(template_declaration.type)
template_declaration.install(strategy)
end
end | [
"def",
"install_templates",
"(",
"rambafile",
")",
"# We always clear previously installed templates to avoid conflicts in different versions",
"clear_installed_templates",
"templates",
"=",
"rambafile",
"[",
"TEMPLATES_KEY",
"]",
"if",
"!",
"templates",
"||",
"templates",
".",
"count",
"==",
"0",
"puts",
"'You must specify at least one template in Rambafile under the key *templates*'",
".",
"red",
"return",
"end",
"# Mapping hashes to model objects",
"templates",
"=",
"rambafile",
"[",
"TEMPLATES_KEY",
"]",
".",
"map",
"{",
"|",
"template_hash",
"|",
"Generamba",
"::",
"TemplateDeclaration",
".",
"new",
"(",
"template_hash",
")",
"}",
"catalogs",
"=",
"rambafile",
"[",
"CATALOGS_KEY",
"]",
"# If there is at least one template from catalogs, we should update our local copy of the catalog",
"update_catalogs_if_needed",
"(",
"catalogs",
",",
"templates",
")",
"templates",
".",
"each",
"do",
"|",
"template_declaration",
"|",
"strategy",
"=",
"@installer_factory",
".",
"installer_for_type",
"(",
"template_declaration",
".",
"type",
")",
"template_declaration",
".",
"install",
"(",
"strategy",
")",
"end",
"end"
] | This method parses Rambafile, serializes templates hashes into model objects and install them | [
"This",
"method",
"parses",
"Rambafile",
"serializes",
"templates",
"hashes",
"into",
"model",
"objects",
"and",
"install",
"them"
] | 9ef343805f3a66f58bc36e120e822d5436a4da97 | https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/processor/template_processor.rb#L20-L44 | train |
strongself/Generamba | lib/generamba/template/processor/template_processor.rb | Generamba.TemplateProcessor.clear_installed_templates | def clear_installed_templates
install_path = Pathname.new(TEMPLATES_FOLDER)
FileUtils.rm_rf(Dir.glob(install_path))
end | ruby | def clear_installed_templates
install_path = Pathname.new(TEMPLATES_FOLDER)
FileUtils.rm_rf(Dir.glob(install_path))
end | [
"def",
"clear_installed_templates",
"install_path",
"=",
"Pathname",
".",
"new",
"(",
"TEMPLATES_FOLDER",
")",
"FileUtils",
".",
"rm_rf",
"(",
"Dir",
".",
"glob",
"(",
"install_path",
")",
")",
"end"
] | Clears all of the currently installed templates | [
"Clears",
"all",
"of",
"the",
"currently",
"installed",
"templates"
] | 9ef343805f3a66f58bc36e120e822d5436a4da97 | https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/processor/template_processor.rb#L49-L52 | train |
strongself/Generamba | lib/generamba/template/processor/template_processor.rb | Generamba.TemplateProcessor.update_catalogs_if_needed | def update_catalogs_if_needed(catalogs, templates)
needs_update = templates.any? {|template| template.type == TemplateDeclarationType::CATALOG_TEMPLATE}
return unless needs_update
terminator = CatalogTerminator.new
terminator.remove_all_catalogs
puts('Updating shared generamba-catalog specs...')
@catalog_downloader.download_catalog(GENERAMBA_CATALOG_NAME, RAMBLER_CATALOG_REPO)
return unless catalogs != nil && catalogs.count > 0
catalogs.each do |catalog_url|
catalog_name = catalog_url.split('://').last
catalog_name = catalog_name.gsub('/', '-');
puts("Updating #{catalog_name} specs...")
@catalog_downloader.download_catalog(catalog_name, catalog_url)
end
end | ruby | def update_catalogs_if_needed(catalogs, templates)
needs_update = templates.any? {|template| template.type == TemplateDeclarationType::CATALOG_TEMPLATE}
return unless needs_update
terminator = CatalogTerminator.new
terminator.remove_all_catalogs
puts('Updating shared generamba-catalog specs...')
@catalog_downloader.download_catalog(GENERAMBA_CATALOG_NAME, RAMBLER_CATALOG_REPO)
return unless catalogs != nil && catalogs.count > 0
catalogs.each do |catalog_url|
catalog_name = catalog_url.split('://').last
catalog_name = catalog_name.gsub('/', '-');
puts("Updating #{catalog_name} specs...")
@catalog_downloader.download_catalog(catalog_name, catalog_url)
end
end | [
"def",
"update_catalogs_if_needed",
"(",
"catalogs",
",",
"templates",
")",
"needs_update",
"=",
"templates",
".",
"any?",
"{",
"|",
"template",
"|",
"template",
".",
"type",
"==",
"TemplateDeclarationType",
"::",
"CATALOG_TEMPLATE",
"}",
"return",
"unless",
"needs_update",
"terminator",
"=",
"CatalogTerminator",
".",
"new",
"terminator",
".",
"remove_all_catalogs",
"puts",
"(",
"'Updating shared generamba-catalog specs...'",
")",
"@catalog_downloader",
".",
"download_catalog",
"(",
"GENERAMBA_CATALOG_NAME",
",",
"RAMBLER_CATALOG_REPO",
")",
"return",
"unless",
"catalogs",
"!=",
"nil",
"&&",
"catalogs",
".",
"count",
">",
"0",
"catalogs",
".",
"each",
"do",
"|",
"catalog_url",
"|",
"catalog_name",
"=",
"catalog_url",
".",
"split",
"(",
"'://'",
")",
".",
"last",
"catalog_name",
"=",
"catalog_name",
".",
"gsub",
"(",
"'/'",
",",
"'-'",
")",
";",
"puts",
"(",
"\"Updating #{catalog_name} specs...\"",
")",
"@catalog_downloader",
".",
"download_catalog",
"(",
"catalog_name",
",",
"catalog_url",
")",
"end",
"end"
] | Clones remote template catalogs to the local directory | [
"Clones",
"remote",
"template",
"catalogs",
"to",
"the",
"local",
"directory"
] | 9ef343805f3a66f58bc36e120e822d5436a4da97 | https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/processor/template_processor.rb#L55-L73 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/scheme.rb | Xcodeproj.XCScheme.configure_with_targets | def configure_with_targets(runnable_target, test_target, launch_target: false)
if runnable_target
add_build_target(runnable_target)
set_launch_target(runnable_target) if launch_target
end
if test_target
add_build_target(test_target, false) if test_target != runnable_target
add_test_target(test_target)
end
end | ruby | def configure_with_targets(runnable_target, test_target, launch_target: false)
if runnable_target
add_build_target(runnable_target)
set_launch_target(runnable_target) if launch_target
end
if test_target
add_build_target(test_target, false) if test_target != runnable_target
add_test_target(test_target)
end
end | [
"def",
"configure_with_targets",
"(",
"runnable_target",
",",
"test_target",
",",
"launch_target",
":",
"false",
")",
"if",
"runnable_target",
"add_build_target",
"(",
"runnable_target",
")",
"set_launch_target",
"(",
"runnable_target",
")",
"if",
"launch_target",
"end",
"if",
"test_target",
"add_build_target",
"(",
"test_target",
",",
"false",
")",
"if",
"test_target",
"!=",
"runnable_target",
"add_test_target",
"(",
"test_target",
")",
"end",
"end"
] | Create a XCScheme either from scratch or using an existing file
@param [String] file_path
The path of the existing .xcscheme file. If nil will create an empty scheme
Convenience method to quickly add app and test targets to a new scheme.
It will add the runnable_target to the Build, Launch and Profile actions
and the test_target to the Build and Test actions
@param [Xcodeproj::Project::Object::PBXAbstractTarget] runnable_target
The target to use for the 'Run', 'Profile' and 'Analyze' actions
@param [Xcodeproj::Project::Object::PBXAbstractTarget] test_target
The target to use for the 'Test' action
@param [Boolean] launch_target
Determines if the runnable_target is launchable. | [
"Create",
"a",
"XCScheme",
"either",
"from",
"scratch",
"or",
"using",
"an",
"existing",
"file"
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/scheme.rb#L72-L81 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/scheme.rb | Xcodeproj.XCScheme.set_launch_target | def set_launch_target(build_target)
launch_runnable = BuildableProductRunnable.new(build_target, 0)
launch_action.buildable_product_runnable = launch_runnable
profile_runnable = BuildableProductRunnable.new(build_target)
profile_action.buildable_product_runnable = profile_runnable
macro_exp = MacroExpansion.new(build_target)
test_action.add_macro_expansion(macro_exp)
end | ruby | def set_launch_target(build_target)
launch_runnable = BuildableProductRunnable.new(build_target, 0)
launch_action.buildable_product_runnable = launch_runnable
profile_runnable = BuildableProductRunnable.new(build_target)
profile_action.buildable_product_runnable = profile_runnable
macro_exp = MacroExpansion.new(build_target)
test_action.add_macro_expansion(macro_exp)
end | [
"def",
"set_launch_target",
"(",
"build_target",
")",
"launch_runnable",
"=",
"BuildableProductRunnable",
".",
"new",
"(",
"build_target",
",",
"0",
")",
"launch_action",
".",
"buildable_product_runnable",
"=",
"launch_runnable",
"profile_runnable",
"=",
"BuildableProductRunnable",
".",
"new",
"(",
"build_target",
")",
"profile_action",
".",
"buildable_product_runnable",
"=",
"profile_runnable",
"macro_exp",
"=",
"MacroExpansion",
".",
"new",
"(",
"build_target",
")",
"test_action",
".",
"add_macro_expansion",
"(",
"macro_exp",
")",
"end"
] | Sets a runnable target to be the target of the launch action of the scheme.
@param [Xcodeproj::Project::Object::AbstractTarget] build_target
A target used by scheme in the launch step. | [
"Sets",
"a",
"runnable",
"target",
"to",
"be",
"the",
"target",
"of",
"the",
"launch",
"action",
"of",
"the",
"scheme",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/scheme.rb#L220-L229 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/scheme.rb | Xcodeproj.XCScheme.save_as | def save_as(project_path, name, shared = true)
scheme_folder_path = if shared
self.class.shared_data_dir(project_path)
else
self.class.user_data_dir(project_path)
end
scheme_folder_path.mkpath
scheme_path = scheme_folder_path + "#{name}.xcscheme"
@file_path = scheme_path
File.open(scheme_path, 'w') do |f|
f.write(to_s)
end
end | ruby | def save_as(project_path, name, shared = true)
scheme_folder_path = if shared
self.class.shared_data_dir(project_path)
else
self.class.user_data_dir(project_path)
end
scheme_folder_path.mkpath
scheme_path = scheme_folder_path + "#{name}.xcscheme"
@file_path = scheme_path
File.open(scheme_path, 'w') do |f|
f.write(to_s)
end
end | [
"def",
"save_as",
"(",
"project_path",
",",
"name",
",",
"shared",
"=",
"true",
")",
"scheme_folder_path",
"=",
"if",
"shared",
"self",
".",
"class",
".",
"shared_data_dir",
"(",
"project_path",
")",
"else",
"self",
".",
"class",
".",
"user_data_dir",
"(",
"project_path",
")",
"end",
"scheme_folder_path",
".",
"mkpath",
"scheme_path",
"=",
"scheme_folder_path",
"+",
"\"#{name}.xcscheme\"",
"@file_path",
"=",
"scheme_path",
"File",
".",
"open",
"(",
"scheme_path",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"to_s",
")",
"end",
"end"
] | Serializes the current state of the object to a ".xcscheme" file.
@param [String, Pathname] project_path
The path where the ".xcscheme" file should be stored.
@param [String] name
The name of the scheme, to have ".xcscheme" appended.
@param [Boolean] shared
true => if the scheme must be a shared scheme (default value)
false => if the scheme must be a user scheme
@return [void]
@example Saving a scheme
scheme.save_as('path/to/Project.xcodeproj') #=> true | [
"Serializes",
"the",
"current",
"state",
"of",
"the",
"object",
"to",
"a",
".",
"xcscheme",
"file",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/scheme.rb#L310-L322 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/project.rb | Xcodeproj.Project.initialize_from_file | def initialize_from_file
pbxproj_path = path + 'project.pbxproj'
plist = Plist.read_from_path(pbxproj_path.to_s)
root_object.remove_referrer(self) if root_object
@root_object = new_from_plist(plist['rootObject'], plist['objects'], self)
@archive_version = plist['archiveVersion']
@object_version = plist['objectVersion']
@classes = plist['classes'] || {}
@dirty = false
unless root_object
raise "[Xcodeproj] Unable to find a root object in #{pbxproj_path}."
end
if archive_version.to_i > Constants::LAST_KNOWN_ARCHIVE_VERSION
raise '[Xcodeproj] Unknown archive version.'
end
if object_version.to_i > Constants::LAST_KNOWN_OBJECT_VERSION
raise '[Xcodeproj] Unknown object version.'
end
# Projects can have product_ref_groups that are not listed in the main_groups["Products"]
root_object.product_ref_group ||= root_object.main_group['Products'] || root_object.main_group.new_group('Products')
end | ruby | def initialize_from_file
pbxproj_path = path + 'project.pbxproj'
plist = Plist.read_from_path(pbxproj_path.to_s)
root_object.remove_referrer(self) if root_object
@root_object = new_from_plist(plist['rootObject'], plist['objects'], self)
@archive_version = plist['archiveVersion']
@object_version = plist['objectVersion']
@classes = plist['classes'] || {}
@dirty = false
unless root_object
raise "[Xcodeproj] Unable to find a root object in #{pbxproj_path}."
end
if archive_version.to_i > Constants::LAST_KNOWN_ARCHIVE_VERSION
raise '[Xcodeproj] Unknown archive version.'
end
if object_version.to_i > Constants::LAST_KNOWN_OBJECT_VERSION
raise '[Xcodeproj] Unknown object version.'
end
# Projects can have product_ref_groups that are not listed in the main_groups["Products"]
root_object.product_ref_group ||= root_object.main_group['Products'] || root_object.main_group.new_group('Products')
end | [
"def",
"initialize_from_file",
"pbxproj_path",
"=",
"path",
"+",
"'project.pbxproj'",
"plist",
"=",
"Plist",
".",
"read_from_path",
"(",
"pbxproj_path",
".",
"to_s",
")",
"root_object",
".",
"remove_referrer",
"(",
"self",
")",
"if",
"root_object",
"@root_object",
"=",
"new_from_plist",
"(",
"plist",
"[",
"'rootObject'",
"]",
",",
"plist",
"[",
"'objects'",
"]",
",",
"self",
")",
"@archive_version",
"=",
"plist",
"[",
"'archiveVersion'",
"]",
"@object_version",
"=",
"plist",
"[",
"'objectVersion'",
"]",
"@classes",
"=",
"plist",
"[",
"'classes'",
"]",
"||",
"{",
"}",
"@dirty",
"=",
"false",
"unless",
"root_object",
"raise",
"\"[Xcodeproj] Unable to find a root object in #{pbxproj_path}.\"",
"end",
"if",
"archive_version",
".",
"to_i",
">",
"Constants",
"::",
"LAST_KNOWN_ARCHIVE_VERSION",
"raise",
"'[Xcodeproj] Unknown archive version.'",
"end",
"if",
"object_version",
".",
"to_i",
">",
"Constants",
"::",
"LAST_KNOWN_OBJECT_VERSION",
"raise",
"'[Xcodeproj] Unknown object version.'",
"end",
"# Projects can have product_ref_groups that are not listed in the main_groups[\"Products\"]",
"root_object",
".",
"product_ref_group",
"||=",
"root_object",
".",
"main_group",
"[",
"'Products'",
"]",
"||",
"root_object",
".",
"main_group",
".",
"new_group",
"(",
"'Products'",
")",
"end"
] | Initializes the instance with the project stored in the `path` attribute. | [
"Initializes",
"the",
"instance",
"with",
"the",
"project",
"stored",
"in",
"the",
"path",
"attribute",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L208-L232 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/project.rb | Xcodeproj.Project.to_tree_hash | def to_tree_hash
hash = {}
objects_dictionary = {}
hash['objects'] = objects_dictionary
hash['archiveVersion'] = archive_version.to_s
hash['objectVersion'] = object_version.to_s
hash['classes'] = classes
hash['rootObject'] = root_object.to_tree_hash
hash
end | ruby | def to_tree_hash
hash = {}
objects_dictionary = {}
hash['objects'] = objects_dictionary
hash['archiveVersion'] = archive_version.to_s
hash['objectVersion'] = object_version.to_s
hash['classes'] = classes
hash['rootObject'] = root_object.to_tree_hash
hash
end | [
"def",
"to_tree_hash",
"hash",
"=",
"{",
"}",
"objects_dictionary",
"=",
"{",
"}",
"hash",
"[",
"'objects'",
"]",
"=",
"objects_dictionary",
"hash",
"[",
"'archiveVersion'",
"]",
"=",
"archive_version",
".",
"to_s",
"hash",
"[",
"'objectVersion'",
"]",
"=",
"object_version",
".",
"to_s",
"hash",
"[",
"'classes'",
"]",
"=",
"classes",
"hash",
"[",
"'rootObject'",
"]",
"=",
"root_object",
".",
"to_tree_hash",
"hash",
"end"
] | Converts the objects tree to a hash substituting the hash
of the referenced to their UUID reference. As a consequence the hash of
an object might appear multiple times and the information about their
uniqueness is lost.
This method is designed to work in conjunction with {Hash#recursive_diff}
to provide a complete, yet readable, diff of two projects *not* affected
by differences in UUIDs.
@return [Hash] a hash representation of the project different from the
plist one. | [
"Converts",
"the",
"objects",
"tree",
"to",
"a",
"hash",
"substituting",
"the",
"hash",
"of",
"the",
"referenced",
"to",
"their",
"UUID",
"reference",
".",
"As",
"a",
"consequence",
"the",
"hash",
"of",
"an",
"object",
"might",
"appear",
"multiple",
"times",
"and",
"the",
"information",
"about",
"their",
"uniqueness",
"is",
"lost",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L320-L329 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/project.rb | Xcodeproj.Project.generate_available_uuid_list | def generate_available_uuid_list(count = 100)
new_uuids = (0..count).map { SecureRandom.hex(12).upcase }
uniques = (new_uuids - (@generated_uuids + uuids))
@generated_uuids += uniques
@available_uuids += uniques
end | ruby | def generate_available_uuid_list(count = 100)
new_uuids = (0..count).map { SecureRandom.hex(12).upcase }
uniques = (new_uuids - (@generated_uuids + uuids))
@generated_uuids += uniques
@available_uuids += uniques
end | [
"def",
"generate_available_uuid_list",
"(",
"count",
"=",
"100",
")",
"new_uuids",
"=",
"(",
"0",
"..",
"count",
")",
".",
"map",
"{",
"SecureRandom",
".",
"hex",
"(",
"12",
")",
".",
"upcase",
"}",
"uniques",
"=",
"(",
"new_uuids",
"-",
"(",
"@generated_uuids",
"+",
"uuids",
")",
")",
"@generated_uuids",
"+=",
"uniques",
"@available_uuids",
"+=",
"uniques",
"end"
] | Pre-generates the given number of UUIDs. Useful for optimizing
performance when the rough number of objects that will be created is
known in advance.
@param [Integer] count
the number of UUIDs that should be generated.
@note This method might generated a minor number of uniques UUIDs than
the given count, because some might be duplicated a thus will be
discarded.
@return [void] | [
"Pre",
"-",
"generates",
"the",
"given",
"number",
"of",
"UUIDs",
".",
"Useful",
"for",
"optimizing",
"performance",
"when",
"the",
"rough",
"number",
"of",
"objects",
"that",
"will",
"be",
"created",
"is",
"known",
"in",
"advance",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L479-L484 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/project.rb | Xcodeproj.Project.reference_for_path | def reference_for_path(absolute_path)
absolute_pathname = Pathname.new(absolute_path)
unless absolute_pathname.absolute?
raise ArgumentError, "Paths must be absolute #{absolute_path}"
end
objects.find do |child|
child.isa == 'PBXFileReference' && child.real_path == absolute_pathname
end
end | ruby | def reference_for_path(absolute_path)
absolute_pathname = Pathname.new(absolute_path)
unless absolute_pathname.absolute?
raise ArgumentError, "Paths must be absolute #{absolute_path}"
end
objects.find do |child|
child.isa == 'PBXFileReference' && child.real_path == absolute_pathname
end
end | [
"def",
"reference_for_path",
"(",
"absolute_path",
")",
"absolute_pathname",
"=",
"Pathname",
".",
"new",
"(",
"absolute_path",
")",
"unless",
"absolute_pathname",
".",
"absolute?",
"raise",
"ArgumentError",
",",
"\"Paths must be absolute #{absolute_path}\"",
"end",
"objects",
".",
"find",
"do",
"|",
"child",
"|",
"child",
".",
"isa",
"==",
"'PBXFileReference'",
"&&",
"child",
".",
"real_path",
"==",
"absolute_pathname",
"end",
"end"
] | Returns the file reference for the given absolute path.
@param [#to_s] absolute_path
The absolute path of the file whose reference is needed.
@return [PBXFileReference] The file reference.
@return [Nil] If no file reference could be found. | [
"Returns",
"the",
"file",
"reference",
"for",
"the",
"given",
"absolute",
"path",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L553-L563 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/project.rb | Xcodeproj.Project.embedded_targets_in_native_target | def embedded_targets_in_native_target(native_target)
native_targets.select do |target|
host_targets_for_embedded_target(target).map(&:uuid).include? native_target.uuid
end
end | ruby | def embedded_targets_in_native_target(native_target)
native_targets.select do |target|
host_targets_for_embedded_target(target).map(&:uuid).include? native_target.uuid
end
end | [
"def",
"embedded_targets_in_native_target",
"(",
"native_target",
")",
"native_targets",
".",
"select",
"do",
"|",
"target",
"|",
"host_targets_for_embedded_target",
"(",
"target",
")",
".",
"map",
"(",
":uuid",
")",
".",
"include?",
"native_target",
".",
"uuid",
"end",
"end"
] | Checks the native target for any targets in the project
that are dependent on the native target and would be
embedded in it at build time
@param [PBXNativeTarget] native target to check for
embedded targets
@return [Array<PBXNativeTarget>] A list of all targets that
are embedded in the passed in target | [
"Checks",
"the",
"native",
"target",
"for",
"any",
"targets",
"in",
"the",
"project",
"that",
"are",
"dependent",
"on",
"the",
"native",
"target",
"and",
"would",
"be",
"embedded",
"in",
"it",
"at",
"build",
"time"
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L590-L594 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/project.rb | Xcodeproj.Project.host_targets_for_embedded_target | def host_targets_for_embedded_target(embedded_target)
native_targets.select do |native_target|
((embedded_target.uuid != native_target.uuid) &&
(native_target.dependencies.map(&:native_target_uuid).include? embedded_target.uuid))
end
end | ruby | def host_targets_for_embedded_target(embedded_target)
native_targets.select do |native_target|
((embedded_target.uuid != native_target.uuid) &&
(native_target.dependencies.map(&:native_target_uuid).include? embedded_target.uuid))
end
end | [
"def",
"host_targets_for_embedded_target",
"(",
"embedded_target",
")",
"native_targets",
".",
"select",
"do",
"|",
"native_target",
"|",
"(",
"(",
"embedded_target",
".",
"uuid",
"!=",
"native_target",
".",
"uuid",
")",
"&&",
"(",
"native_target",
".",
"dependencies",
".",
"map",
"(",
":native_target_uuid",
")",
".",
"include?",
"embedded_target",
".",
"uuid",
")",
")",
"end",
"end"
] | Returns the native targets, in which the embedded target is
embedded. This works by traversing the targets to find those
where the target is a dependency.
@param [PBXNativeTarget] native target that might be embedded
in another target
@return [Array<PBXNativeTarget>] the native targets that host the
embedded target | [
"Returns",
"the",
"native",
"targets",
"in",
"which",
"the",
"embedded",
"target",
"is",
"embedded",
".",
"This",
"works",
"by",
"traversing",
"the",
"targets",
"to",
"find",
"those",
"where",
"the",
"target",
"is",
"a",
"dependency",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L606-L611 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/project.rb | Xcodeproj.Project.new_resources_bundle | def new_resources_bundle(name, platform, product_group = nil)
product_group ||= products_group
ProjectHelper.new_resources_bundle(self, name, platform, product_group)
end | ruby | def new_resources_bundle(name, platform, product_group = nil)
product_group ||= products_group
ProjectHelper.new_resources_bundle(self, name, platform, product_group)
end | [
"def",
"new_resources_bundle",
"(",
"name",
",",
"platform",
",",
"product_group",
"=",
"nil",
")",
"product_group",
"||=",
"products_group",
"ProjectHelper",
".",
"new_resources_bundle",
"(",
"self",
",",
"name",
",",
"platform",
",",
"product_group",
")",
"end"
] | Creates a new resource bundles target and adds it to the project.
The target is configured for the given platform and its file reference it
is added to the {products_group}.
The target is pre-populated with common build settings
@param [String] name
the name of the resources bundle.
@param [Symbol] platform
the platform of the resources bundle. Can be `:ios` or `:osx`.
@return [PBXNativeTarget] the target. | [
"Creates",
"a",
"new",
"resource",
"bundles",
"target",
"and",
"adds",
"it",
"to",
"the",
"project",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L734-L737 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/project.rb | Xcodeproj.Project.add_build_configuration | def add_build_configuration(name, type)
build_configuration_list = root_object.build_configuration_list
if build_configuration = build_configuration_list[name]
build_configuration
else
build_configuration = new(XCBuildConfiguration)
build_configuration.name = name
common_settings = Constants::PROJECT_DEFAULT_BUILD_SETTINGS
settings = ProjectHelper.deep_dup(common_settings[:all])
settings.merge!(ProjectHelper.deep_dup(common_settings[type]))
build_configuration.build_settings = settings
build_configuration_list.build_configurations << build_configuration
build_configuration
end
end | ruby | def add_build_configuration(name, type)
build_configuration_list = root_object.build_configuration_list
if build_configuration = build_configuration_list[name]
build_configuration
else
build_configuration = new(XCBuildConfiguration)
build_configuration.name = name
common_settings = Constants::PROJECT_DEFAULT_BUILD_SETTINGS
settings = ProjectHelper.deep_dup(common_settings[:all])
settings.merge!(ProjectHelper.deep_dup(common_settings[type]))
build_configuration.build_settings = settings
build_configuration_list.build_configurations << build_configuration
build_configuration
end
end | [
"def",
"add_build_configuration",
"(",
"name",
",",
"type",
")",
"build_configuration_list",
"=",
"root_object",
".",
"build_configuration_list",
"if",
"build_configuration",
"=",
"build_configuration_list",
"[",
"name",
"]",
"build_configuration",
"else",
"build_configuration",
"=",
"new",
"(",
"XCBuildConfiguration",
")",
"build_configuration",
".",
"name",
"=",
"name",
"common_settings",
"=",
"Constants",
"::",
"PROJECT_DEFAULT_BUILD_SETTINGS",
"settings",
"=",
"ProjectHelper",
".",
"deep_dup",
"(",
"common_settings",
"[",
":all",
"]",
")",
"settings",
".",
"merge!",
"(",
"ProjectHelper",
".",
"deep_dup",
"(",
"common_settings",
"[",
"type",
"]",
")",
")",
"build_configuration",
".",
"build_settings",
"=",
"settings",
"build_configuration_list",
".",
"build_configurations",
"<<",
"build_configuration",
"build_configuration",
"end",
"end"
] | Adds a new build configuration to the project and populates its with
default settings according to the provided type.
@param [String] name
The name of the build configuration.
@param [Symbol] type
The type of the build configuration used to populate the build
settings, must be :debug or :release.
@return [XCBuildConfiguration] The new build configuration. | [
"Adds",
"a",
"new",
"build",
"configuration",
"to",
"the",
"project",
"and",
"populates",
"its",
"with",
"default",
"settings",
"according",
"to",
"the",
"provided",
"type",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L782-L796 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/config.rb | Xcodeproj.Config.save_as | def save_as(pathname, prefix = nil)
if File.exist?(pathname)
return if Config.new(pathname) == self
end
pathname.open('w') { |file| file << to_s(prefix) }
end | ruby | def save_as(pathname, prefix = nil)
if File.exist?(pathname)
return if Config.new(pathname) == self
end
pathname.open('w') { |file| file << to_s(prefix) }
end | [
"def",
"save_as",
"(",
"pathname",
",",
"prefix",
"=",
"nil",
")",
"if",
"File",
".",
"exist?",
"(",
"pathname",
")",
"return",
"if",
"Config",
".",
"new",
"(",
"pathname",
")",
"==",
"self",
"end",
"pathname",
".",
"open",
"(",
"'w'",
")",
"{",
"|",
"file",
"|",
"file",
"<<",
"to_s",
"(",
"prefix",
")",
"}",
"end"
] | Writes the serialized representation of the internal data to the given
path.
@param [Pathname] pathname
The file where the data should be written to.
@return [void] | [
"Writes",
"the",
"serialized",
"representation",
"of",
"the",
"internal",
"data",
"to",
"the",
"given",
"path",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/config.rb#L104-L110 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/config.rb | Xcodeproj.Config.hash_from_file_content | def hash_from_file_content(string)
hash = {}
string.split("\n").each do |line|
uncommented_line = strip_comment(line)
if include = extract_include(uncommented_line)
@includes.push normalized_xcconfig_path(include)
else
key, value = extract_key_value(uncommented_line)
next unless key
value.gsub!(INHERITED_REGEXP) { |m| hash.fetch(key, m) }
hash[key] = value
end
end
hash
end | ruby | def hash_from_file_content(string)
hash = {}
string.split("\n").each do |line|
uncommented_line = strip_comment(line)
if include = extract_include(uncommented_line)
@includes.push normalized_xcconfig_path(include)
else
key, value = extract_key_value(uncommented_line)
next unless key
value.gsub!(INHERITED_REGEXP) { |m| hash.fetch(key, m) }
hash[key] = value
end
end
hash
end | [
"def",
"hash_from_file_content",
"(",
"string",
")",
"hash",
"=",
"{",
"}",
"string",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"each",
"do",
"|",
"line",
"|",
"uncommented_line",
"=",
"strip_comment",
"(",
"line",
")",
"if",
"include",
"=",
"extract_include",
"(",
"uncommented_line",
")",
"@includes",
".",
"push",
"normalized_xcconfig_path",
"(",
"include",
")",
"else",
"key",
",",
"value",
"=",
"extract_key_value",
"(",
"uncommented_line",
")",
"next",
"unless",
"key",
"value",
".",
"gsub!",
"(",
"INHERITED_REGEXP",
")",
"{",
"|",
"m",
"|",
"hash",
".",
"fetch",
"(",
"key",
",",
"m",
")",
"}",
"hash",
"[",
"key",
"]",
"=",
"value",
"end",
"end",
"hash",
"end"
] | Returns a hash from the string representation of an Xcconfig file.
@param [String] string
The string representation of an xcconfig file.
@return [Hash] the hash containing the xcconfig data. | [
"Returns",
"a",
"hash",
"from",
"the",
"string",
"representation",
"of",
"an",
"Xcconfig",
"file",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/config.rb#L273-L287 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/config.rb | Xcodeproj.Config.merge_attributes! | def merge_attributes!(attributes)
@attributes.merge!(attributes) do |_, v1, v2|
v1 = v1.strip
v2 = v2.strip
v1_split = v1.shellsplit
v2_split = v2.shellsplit
if (v2_split - v1_split).empty? || v1_split.first(v2_split.size) == v2_split
v1
elsif v2_split.first(v1_split.size) == v1_split
v2
else
"#{v1} #{v2}"
end
end
end | ruby | def merge_attributes!(attributes)
@attributes.merge!(attributes) do |_, v1, v2|
v1 = v1.strip
v2 = v2.strip
v1_split = v1.shellsplit
v2_split = v2.shellsplit
if (v2_split - v1_split).empty? || v1_split.first(v2_split.size) == v2_split
v1
elsif v2_split.first(v1_split.size) == v1_split
v2
else
"#{v1} #{v2}"
end
end
end | [
"def",
"merge_attributes!",
"(",
"attributes",
")",
"@attributes",
".",
"merge!",
"(",
"attributes",
")",
"do",
"|",
"_",
",",
"v1",
",",
"v2",
"|",
"v1",
"=",
"v1",
".",
"strip",
"v2",
"=",
"v2",
".",
"strip",
"v1_split",
"=",
"v1",
".",
"shellsplit",
"v2_split",
"=",
"v2",
".",
"shellsplit",
"if",
"(",
"v2_split",
"-",
"v1_split",
")",
".",
"empty?",
"||",
"v1_split",
".",
"first",
"(",
"v2_split",
".",
"size",
")",
"==",
"v2_split",
"v1",
"elsif",
"v2_split",
".",
"first",
"(",
"v1_split",
".",
"size",
")",
"==",
"v1_split",
"v2",
"else",
"\"#{v1} #{v2}\"",
"end",
"end",
"end"
] | Merges the given attributes hash while ensuring values are not duplicated.
@param [Hash] attributes
The attributes hash to merge into @attributes.
@return [void] | [
"Merges",
"the",
"given",
"attributes",
"hash",
"while",
"ensuring",
"values",
"are",
"not",
"duplicated",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/config.rb#L296-L310 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/config.rb | Xcodeproj.Config.extract_key_value | def extract_key_value(line)
match = line.match(KEY_VALUE_PATTERN)
if match
key = match[1]
value = match[2]
[key.strip, value.strip]
else
[]
end
end | ruby | def extract_key_value(line)
match = line.match(KEY_VALUE_PATTERN)
if match
key = match[1]
value = match[2]
[key.strip, value.strip]
else
[]
end
end | [
"def",
"extract_key_value",
"(",
"line",
")",
"match",
"=",
"line",
".",
"match",
"(",
"KEY_VALUE_PATTERN",
")",
"if",
"match",
"key",
"=",
"match",
"[",
"1",
"]",
"value",
"=",
"match",
"[",
"2",
"]",
"[",
"key",
".",
"strip",
",",
"value",
".",
"strip",
"]",
"else",
"[",
"]",
"end",
"end"
] | Returns the key and the value described by the given line of an xcconfig.
@param [String] line
the line to process.
@return [Array] A tuple where the first entry is the key and the second
entry is the value. | [
"Returns",
"the",
"key",
"and",
"the",
"value",
"described",
"by",
"the",
"given",
"line",
"of",
"an",
"xcconfig",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/config.rb#L345-L354 | train |
CocoaPods/Xcodeproj | spec/spec_helper/project_helper.rb | SpecHelper.ProjectHelper.compare_settings | def compare_settings(produced, expected, params)
it 'should match build settings' do
# Find faulty settings in different categories
missing_settings = expected.keys.reject { |k| produced.key?(k) }
unexpected_settings = produced.keys.reject { |k| expected.key?(k) }
wrong_settings = (expected.keys - missing_settings).select do |k|
produced_setting = produced[k]
produced_setting = produced_setting.join(' ') if produced_setting.respond_to? :join
produced_setting != expected[k]
end
# Build pretty description for what is going on
description = []
description << "Doesn't match build settings for \e[1m#{params}\e[0m"
if wrong_settings.count > 0
description << 'Wrong build settings:'
description += wrong_settings.map { |s| "* #{s.to_s.yellow} is #{produced[s].to_s.red}, but should be #{expected[s].to_s.green}" }
description << ''
end
if missing_settings.count > 0
description << 'Missing build settings:'
description << missing_settings.map { |s| "* #{s.to_s.red} (#{expected[s]})" }
description << ''
end
if unexpected_settings.count > 0
description << 'Unexpected additional build settings:'
description += unexpected_settings.map { |s| "* #{s.to_s.green} (#{produced[s]})" }
description << ''
end
# Expect
faulty_settings = missing_settings + unexpected_settings + wrong_settings
faulty_settings.should.satisfy(description * "\n") do
faulty_settings.length == 0
end
end
end | ruby | def compare_settings(produced, expected, params)
it 'should match build settings' do
# Find faulty settings in different categories
missing_settings = expected.keys.reject { |k| produced.key?(k) }
unexpected_settings = produced.keys.reject { |k| expected.key?(k) }
wrong_settings = (expected.keys - missing_settings).select do |k|
produced_setting = produced[k]
produced_setting = produced_setting.join(' ') if produced_setting.respond_to? :join
produced_setting != expected[k]
end
# Build pretty description for what is going on
description = []
description << "Doesn't match build settings for \e[1m#{params}\e[0m"
if wrong_settings.count > 0
description << 'Wrong build settings:'
description += wrong_settings.map { |s| "* #{s.to_s.yellow} is #{produced[s].to_s.red}, but should be #{expected[s].to_s.green}" }
description << ''
end
if missing_settings.count > 0
description << 'Missing build settings:'
description << missing_settings.map { |s| "* #{s.to_s.red} (#{expected[s]})" }
description << ''
end
if unexpected_settings.count > 0
description << 'Unexpected additional build settings:'
description += unexpected_settings.map { |s| "* #{s.to_s.green} (#{produced[s]})" }
description << ''
end
# Expect
faulty_settings = missing_settings + unexpected_settings + wrong_settings
faulty_settings.should.satisfy(description * "\n") do
faulty_settings.length == 0
end
end
end | [
"def",
"compare_settings",
"(",
"produced",
",",
"expected",
",",
"params",
")",
"it",
"'should match build settings'",
"do",
"# Find faulty settings in different categories",
"missing_settings",
"=",
"expected",
".",
"keys",
".",
"reject",
"{",
"|",
"k",
"|",
"produced",
".",
"key?",
"(",
"k",
")",
"}",
"unexpected_settings",
"=",
"produced",
".",
"keys",
".",
"reject",
"{",
"|",
"k",
"|",
"expected",
".",
"key?",
"(",
"k",
")",
"}",
"wrong_settings",
"=",
"(",
"expected",
".",
"keys",
"-",
"missing_settings",
")",
".",
"select",
"do",
"|",
"k",
"|",
"produced_setting",
"=",
"produced",
"[",
"k",
"]",
"produced_setting",
"=",
"produced_setting",
".",
"join",
"(",
"' '",
")",
"if",
"produced_setting",
".",
"respond_to?",
":join",
"produced_setting",
"!=",
"expected",
"[",
"k",
"]",
"end",
"# Build pretty description for what is going on",
"description",
"=",
"[",
"]",
"description",
"<<",
"\"Doesn't match build settings for \\e[1m#{params}\\e[0m\"",
"if",
"wrong_settings",
".",
"count",
">",
"0",
"description",
"<<",
"'Wrong build settings:'",
"description",
"+=",
"wrong_settings",
".",
"map",
"{",
"|",
"s",
"|",
"\"* #{s.to_s.yellow} is #{produced[s].to_s.red}, but should be #{expected[s].to_s.green}\"",
"}",
"description",
"<<",
"''",
"end",
"if",
"missing_settings",
".",
"count",
">",
"0",
"description",
"<<",
"'Missing build settings:'",
"description",
"<<",
"missing_settings",
".",
"map",
"{",
"|",
"s",
"|",
"\"* #{s.to_s.red} (#{expected[s]})\"",
"}",
"description",
"<<",
"''",
"end",
"if",
"unexpected_settings",
".",
"count",
">",
"0",
"description",
"<<",
"'Unexpected additional build settings:'",
"description",
"+=",
"unexpected_settings",
".",
"map",
"{",
"|",
"s",
"|",
"\"* #{s.to_s.green} (#{produced[s]})\"",
"}",
"description",
"<<",
"''",
"end",
"# Expect",
"faulty_settings",
"=",
"missing_settings",
"+",
"unexpected_settings",
"+",
"wrong_settings",
"faulty_settings",
".",
"should",
".",
"satisfy",
"(",
"description",
"*",
"\"\\n\"",
")",
"do",
"faulty_settings",
".",
"length",
"==",
"0",
"end",
"end",
"end"
] | Generates test cases to compare two settings hashes.
@param [Hash{String => String}] produced
the produced build settings.
@param [Hash{String => String}] expected
the expected build settings.
@param [#to_s] params
the parameters used to construct the produced build settings. | [
"Generates",
"test",
"cases",
"to",
"compare",
"two",
"settings",
"hashes",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/spec/spec_helper/project_helper.rb#L29-L68 | train |
CocoaPods/Xcodeproj | spec/spec_helper/project_helper.rb | SpecHelper.ProjectHelper.load_settings | def load_settings(path, type)
# Load fixture
base_path = Pathname(fixture_path("CommonBuildSettings/configs/#{path}"))
config_fixture = base_path + "#{path}_#{type}.xcconfig"
config = Xcodeproj::Config.new(config_fixture)
settings = config.to_hash
# Filter exclusions
settings = apply_exclusions(settings, EXCLUDED_KEYS)
project_defaults_by_config = Xcodeproj::Constants::PROJECT_DEFAULT_BUILD_SETTINGS
project_defaults = project_defaults_by_config[:all]
project_defaults.merge(project_defaults_by_config[type]) unless type == :base
settings = apply_exclusions(settings, project_defaults)
settings
end | ruby | def load_settings(path, type)
# Load fixture
base_path = Pathname(fixture_path("CommonBuildSettings/configs/#{path}"))
config_fixture = base_path + "#{path}_#{type}.xcconfig"
config = Xcodeproj::Config.new(config_fixture)
settings = config.to_hash
# Filter exclusions
settings = apply_exclusions(settings, EXCLUDED_KEYS)
project_defaults_by_config = Xcodeproj::Constants::PROJECT_DEFAULT_BUILD_SETTINGS
project_defaults = project_defaults_by_config[:all]
project_defaults.merge(project_defaults_by_config[type]) unless type == :base
settings = apply_exclusions(settings, project_defaults)
settings
end | [
"def",
"load_settings",
"(",
"path",
",",
"type",
")",
"# Load fixture",
"base_path",
"=",
"Pathname",
"(",
"fixture_path",
"(",
"\"CommonBuildSettings/configs/#{path}\"",
")",
")",
"config_fixture",
"=",
"base_path",
"+",
"\"#{path}_#{type}.xcconfig\"",
"config",
"=",
"Xcodeproj",
"::",
"Config",
".",
"new",
"(",
"config_fixture",
")",
"settings",
"=",
"config",
".",
"to_hash",
"# Filter exclusions",
"settings",
"=",
"apply_exclusions",
"(",
"settings",
",",
"EXCLUDED_KEYS",
")",
"project_defaults_by_config",
"=",
"Xcodeproj",
"::",
"Constants",
"::",
"PROJECT_DEFAULT_BUILD_SETTINGS",
"project_defaults",
"=",
"project_defaults_by_config",
"[",
":all",
"]",
"project_defaults",
".",
"merge",
"(",
"project_defaults_by_config",
"[",
"type",
"]",
")",
"unless",
"type",
"==",
":base",
"settings",
"=",
"apply_exclusions",
"(",
"settings",
",",
"project_defaults",
")",
"settings",
"end"
] | Load settings from fixtures
@param [String] path
the directory, where the fixture set is located.
@param [Symbol] type
the type, where the specific
@param [Hash{String => String}]
the build settings | [
"Load",
"settings",
"from",
"fixtures"
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/spec/spec_helper/project_helper.rb#L81-L96 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/workspace.rb | Xcodeproj.Workspace.save_as | def save_as(path)
FileUtils.mkdir_p(path)
File.open(File.join(path, 'contents.xcworkspacedata'), 'w') do |out|
out << to_s
end
end | ruby | def save_as(path)
FileUtils.mkdir_p(path)
File.open(File.join(path, 'contents.xcworkspacedata'), 'w') do |out|
out << to_s
end
end | [
"def",
"save_as",
"(",
"path",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"path",
")",
"File",
".",
"open",
"(",
"File",
".",
"join",
"(",
"path",
",",
"'contents.xcworkspacedata'",
")",
",",
"'w'",
")",
"do",
"|",
"out",
"|",
"out",
"<<",
"to_s",
"end",
"end"
] | Saves the workspace at the given `xcworkspace` path.
@param [String] path
the path where to save the project.
@return [void] | [
"Saves",
"the",
"workspace",
"at",
"the",
"given",
"xcworkspace",
"path",
"."
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/workspace.rb#L179-L184 | train |
CocoaPods/Xcodeproj | lib/xcodeproj/workspace.rb | Xcodeproj.Workspace.load_schemes_from_project | def load_schemes_from_project(project_full_path)
schemes = Xcodeproj::Project.schemes project_full_path
schemes.each do |scheme_name|
@schemes[scheme_name] = project_full_path
end
end | ruby | def load_schemes_from_project(project_full_path)
schemes = Xcodeproj::Project.schemes project_full_path
schemes.each do |scheme_name|
@schemes[scheme_name] = project_full_path
end
end | [
"def",
"load_schemes_from_project",
"(",
"project_full_path",
")",
"schemes",
"=",
"Xcodeproj",
"::",
"Project",
".",
"schemes",
"project_full_path",
"schemes",
".",
"each",
"do",
"|",
"scheme_name",
"|",
"@schemes",
"[",
"scheme_name",
"]",
"=",
"project_full_path",
"end",
"end"
] | Load all schemes from project
@param [String] project_full_path
project full path
@return [void] | [
"Load",
"all",
"schemes",
"from",
"project"
] | 3be1684437a6f8e69c7836ad4c85a2b78663272f | https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/workspace.rb#L224-L229 | train |
kmuto/review | lib/epubmaker/epubcommon.rb | EPUBMaker.EPUBCommon.container | def container
@opf_path = opf_path
tmplfile = File.expand_path('./xml/container.xml.erb', ReVIEW::Template::TEMPLATE_DIR)
tmpl = ReVIEW::Template.load(tmplfile)
tmpl.result(binding)
end | ruby | def container
@opf_path = opf_path
tmplfile = File.expand_path('./xml/container.xml.erb', ReVIEW::Template::TEMPLATE_DIR)
tmpl = ReVIEW::Template.load(tmplfile)
tmpl.result(binding)
end | [
"def",
"container",
"@opf_path",
"=",
"opf_path",
"tmplfile",
"=",
"File",
".",
"expand_path",
"(",
"'./xml/container.xml.erb'",
",",
"ReVIEW",
"::",
"Template",
"::",
"TEMPLATE_DIR",
")",
"tmpl",
"=",
"ReVIEW",
"::",
"Template",
".",
"load",
"(",
"tmplfile",
")",
"tmpl",
".",
"result",
"(",
"binding",
")",
"end"
] | Return container content. | [
"Return",
"container",
"content",
"."
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/epubcommon.rb#L118-L123 | train |
kmuto/review | lib/epubmaker/epubcommon.rb | EPUBMaker.EPUBCommon.mytoc | def mytoc
@title = CGI.escapeHTML(@producer.res.v('toctitle'))
@body = %Q( <h1 class="toc-title">#{CGI.escapeHTML(@producer.res.v('toctitle'))}</h1>\n)
if @producer.config['epubmaker']['flattoc'].nil?
@body << hierarchy_ncx('ul')
else
@body << flat_ncx('ul', @producer.config['epubmaker']['flattocindent'])
end
@language = @producer.config['language']
@stylesheets = @producer.config['stylesheet']
tmplfile = if @producer.config['htmlversion'].to_i == 5
File.expand_path('./html/layout-html5.html.erb', ReVIEW::Template::TEMPLATE_DIR)
else
File.expand_path('./html/layout-xhtml1.html.erb', ReVIEW::Template::TEMPLATE_DIR)
end
tmpl = ReVIEW::Template.load(tmplfile)
tmpl.result(binding)
end | ruby | def mytoc
@title = CGI.escapeHTML(@producer.res.v('toctitle'))
@body = %Q( <h1 class="toc-title">#{CGI.escapeHTML(@producer.res.v('toctitle'))}</h1>\n)
if @producer.config['epubmaker']['flattoc'].nil?
@body << hierarchy_ncx('ul')
else
@body << flat_ncx('ul', @producer.config['epubmaker']['flattocindent'])
end
@language = @producer.config['language']
@stylesheets = @producer.config['stylesheet']
tmplfile = if @producer.config['htmlversion'].to_i == 5
File.expand_path('./html/layout-html5.html.erb', ReVIEW::Template::TEMPLATE_DIR)
else
File.expand_path('./html/layout-xhtml1.html.erb', ReVIEW::Template::TEMPLATE_DIR)
end
tmpl = ReVIEW::Template.load(tmplfile)
tmpl.result(binding)
end | [
"def",
"mytoc",
"@title",
"=",
"CGI",
".",
"escapeHTML",
"(",
"@producer",
".",
"res",
".",
"v",
"(",
"'toctitle'",
")",
")",
"@body",
"=",
"%Q( <h1 class=\"toc-title\">#{CGI.escapeHTML(@producer.res.v('toctitle'))}</h1>\\n)",
"if",
"@producer",
".",
"config",
"[",
"'epubmaker'",
"]",
"[",
"'flattoc'",
"]",
".",
"nil?",
"@body",
"<<",
"hierarchy_ncx",
"(",
"'ul'",
")",
"else",
"@body",
"<<",
"flat_ncx",
"(",
"'ul'",
",",
"@producer",
".",
"config",
"[",
"'epubmaker'",
"]",
"[",
"'flattocindent'",
"]",
")",
"end",
"@language",
"=",
"@producer",
".",
"config",
"[",
"'language'",
"]",
"@stylesheets",
"=",
"@producer",
".",
"config",
"[",
"'stylesheet'",
"]",
"tmplfile",
"=",
"if",
"@producer",
".",
"config",
"[",
"'htmlversion'",
"]",
".",
"to_i",
"==",
"5",
"File",
".",
"expand_path",
"(",
"'./html/layout-html5.html.erb'",
",",
"ReVIEW",
"::",
"Template",
"::",
"TEMPLATE_DIR",
")",
"else",
"File",
".",
"expand_path",
"(",
"'./html/layout-xhtml1.html.erb'",
",",
"ReVIEW",
"::",
"Template",
"::",
"TEMPLATE_DIR",
")",
"end",
"tmpl",
"=",
"ReVIEW",
"::",
"Template",
".",
"load",
"(",
"tmplfile",
")",
"tmpl",
".",
"result",
"(",
"binding",
")",
"end"
] | Return own toc content. | [
"Return",
"own",
"toc",
"content",
"."
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/epubcommon.rb#L291-L310 | train |
kmuto/review | lib/review/compiler.rb | ReVIEW.Compiler.compile_inline | def compile_inline(str)
op, arg = /\A@<(\w+)>\{(.*?)\}\z/.match(str).captures
unless inline_defined?(op)
raise CompileError, "no such inline op: #{op}"
end
unless @strategy.respond_to?("inline_#{op}")
raise "strategy does not support inline op: @<#{op}>"
end
@strategy.__send__("inline_#{op}", arg)
rescue => e
error e.message
@strategy.nofunc_text(str)
end | ruby | def compile_inline(str)
op, arg = /\A@<(\w+)>\{(.*?)\}\z/.match(str).captures
unless inline_defined?(op)
raise CompileError, "no such inline op: #{op}"
end
unless @strategy.respond_to?("inline_#{op}")
raise "strategy does not support inline op: @<#{op}>"
end
@strategy.__send__("inline_#{op}", arg)
rescue => e
error e.message
@strategy.nofunc_text(str)
end | [
"def",
"compile_inline",
"(",
"str",
")",
"op",
",",
"arg",
"=",
"/",
"\\A",
"\\w",
"\\{",
"\\}",
"\\z",
"/",
".",
"match",
"(",
"str",
")",
".",
"captures",
"unless",
"inline_defined?",
"(",
"op",
")",
"raise",
"CompileError",
",",
"\"no such inline op: #{op}\"",
"end",
"unless",
"@strategy",
".",
"respond_to?",
"(",
"\"inline_#{op}\"",
")",
"raise",
"\"strategy does not support inline op: @<#{op}>\"",
"end",
"@strategy",
".",
"__send__",
"(",
"\"inline_#{op}\"",
",",
"arg",
")",
"rescue",
"=>",
"e",
"error",
"e",
".",
"message",
"@strategy",
".",
"nofunc_text",
"(",
"str",
")",
"end"
] | called from strategy | [
"called",
"from",
"strategy"
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/review/compiler.rb#L572-L584 | train |
kmuto/review | lib/epubmaker/producer.rb | EPUBMaker.Producer.load | def load(file)
if file.nil? || !File.exist?(file)
raise "Can't open #{file}."
end
loader = ReVIEW::YAMLLoader.new
merge_config(@config.deep_merge(loader.load_file(file)))
end | ruby | def load(file)
if file.nil? || !File.exist?(file)
raise "Can't open #{file}."
end
loader = ReVIEW::YAMLLoader.new
merge_config(@config.deep_merge(loader.load_file(file)))
end | [
"def",
"load",
"(",
"file",
")",
"if",
"file",
".",
"nil?",
"||",
"!",
"File",
".",
"exist?",
"(",
"file",
")",
"raise",
"\"Can't open #{file}.\"",
"end",
"loader",
"=",
"ReVIEW",
"::",
"YAMLLoader",
".",
"new",
"merge_config",
"(",
"@config",
".",
"deep_merge",
"(",
"loader",
".",
"load_file",
"(",
"file",
")",
")",
")",
"end"
] | Take YAML +file+ and update parameter hash. | [
"Take",
"YAML",
"+",
"file",
"+",
"and",
"update",
"parameter",
"hash",
"."
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L40-L46 | train |
kmuto/review | lib/epubmaker/producer.rb | EPUBMaker.Producer.merge_config | def merge_config(config)
@config.deep_merge!(config)
complement
unless @config['epubversion'].nil?
case @config['epubversion'].to_i
when 2
@epub = EPUBMaker::EPUBv2.new(self)
when 3
@epub = EPUBMaker::EPUBv3.new(self)
else
raise "Invalid EPUB version (#{@config['epubversion']}.)"
end
end
if config['language']
ReVIEW::I18n.locale = config['language']
end
support_legacy_maker
end | ruby | def merge_config(config)
@config.deep_merge!(config)
complement
unless @config['epubversion'].nil?
case @config['epubversion'].to_i
when 2
@epub = EPUBMaker::EPUBv2.new(self)
when 3
@epub = EPUBMaker::EPUBv3.new(self)
else
raise "Invalid EPUB version (#{@config['epubversion']}.)"
end
end
if config['language']
ReVIEW::I18n.locale = config['language']
end
support_legacy_maker
end | [
"def",
"merge_config",
"(",
"config",
")",
"@config",
".",
"deep_merge!",
"(",
"config",
")",
"complement",
"unless",
"@config",
"[",
"'epubversion'",
"]",
".",
"nil?",
"case",
"@config",
"[",
"'epubversion'",
"]",
".",
"to_i",
"when",
"2",
"@epub",
"=",
"EPUBMaker",
"::",
"EPUBv2",
".",
"new",
"(",
"self",
")",
"when",
"3",
"@epub",
"=",
"EPUBMaker",
"::",
"EPUBv3",
".",
"new",
"(",
"self",
")",
"else",
"raise",
"\"Invalid EPUB version (#{@config['epubversion']}.)\"",
"end",
"end",
"if",
"config",
"[",
"'language'",
"]",
"ReVIEW",
"::",
"I18n",
".",
"locale",
"=",
"config",
"[",
"'language'",
"]",
"end",
"support_legacy_maker",
"end"
] | Update parameters by merging from new parameter hash +config+. | [
"Update",
"parameters",
"by",
"merging",
"from",
"new",
"parameter",
"hash",
"+",
"config",
"+",
"."
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L77-L95 | train |
kmuto/review | lib/epubmaker/producer.rb | EPUBMaker.Producer.mimetype | def mimetype(wobj)
s = @epub.mimetype
if !s.nil? && !wobj.nil?
wobj.print s
end
end | ruby | def mimetype(wobj)
s = @epub.mimetype
if !s.nil? && !wobj.nil?
wobj.print s
end
end | [
"def",
"mimetype",
"(",
"wobj",
")",
"s",
"=",
"@epub",
".",
"mimetype",
"if",
"!",
"s",
".",
"nil?",
"&&",
"!",
"wobj",
".",
"nil?",
"wobj",
".",
"print",
"s",
"end",
"end"
] | Write mimetype file to IO object +wobj+. | [
"Write",
"mimetype",
"file",
"to",
"IO",
"object",
"+",
"wobj",
"+",
"."
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L98-L103 | train |
kmuto/review | lib/epubmaker/producer.rb | EPUBMaker.Producer.opf | def opf(wobj)
s = @epub.opf
if !s.nil? && !wobj.nil?
wobj.puts s
end
end | ruby | def opf(wobj)
s = @epub.opf
if !s.nil? && !wobj.nil?
wobj.puts s
end
end | [
"def",
"opf",
"(",
"wobj",
")",
"s",
"=",
"@epub",
".",
"opf",
"if",
"!",
"s",
".",
"nil?",
"&&",
"!",
"wobj",
".",
"nil?",
"wobj",
".",
"puts",
"s",
"end",
"end"
] | Write opf file to IO object +wobj+. | [
"Write",
"opf",
"file",
"to",
"IO",
"object",
"+",
"wobj",
"+",
"."
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L106-L111 | train |
kmuto/review | lib/epubmaker/producer.rb | EPUBMaker.Producer.ncx | def ncx(wobj, indentarray = [])
s = @epub.ncx(indentarray)
if !s.nil? && !wobj.nil?
wobj.puts s
end
end | ruby | def ncx(wobj, indentarray = [])
s = @epub.ncx(indentarray)
if !s.nil? && !wobj.nil?
wobj.puts s
end
end | [
"def",
"ncx",
"(",
"wobj",
",",
"indentarray",
"=",
"[",
"]",
")",
"s",
"=",
"@epub",
".",
"ncx",
"(",
"indentarray",
")",
"if",
"!",
"s",
".",
"nil?",
"&&",
"!",
"wobj",
".",
"nil?",
"wobj",
".",
"puts",
"s",
"end",
"end"
] | Write ncx file to IO object +wobj+. +indentarray+ defines prefix
string for each level. | [
"Write",
"ncx",
"file",
"to",
"IO",
"object",
"+",
"wobj",
"+",
".",
"+",
"indentarray",
"+",
"defines",
"prefix",
"string",
"for",
"each",
"level",
"."
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L115-L120 | train |
kmuto/review | lib/epubmaker/producer.rb | EPUBMaker.Producer.container | def container(wobj)
s = @epub.container
if !s.nil? && !wobj.nil?
wobj.puts s
end
end | ruby | def container(wobj)
s = @epub.container
if !s.nil? && !wobj.nil?
wobj.puts s
end
end | [
"def",
"container",
"(",
"wobj",
")",
"s",
"=",
"@epub",
".",
"container",
"if",
"!",
"s",
".",
"nil?",
"&&",
"!",
"wobj",
".",
"nil?",
"wobj",
".",
"puts",
"s",
"end",
"end"
] | Write container file to IO object +wobj+. | [
"Write",
"container",
"file",
"to",
"IO",
"object",
"+",
"wobj",
"+",
"."
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L123-L128 | train |
kmuto/review | lib/epubmaker/producer.rb | EPUBMaker.Producer.colophon | def colophon(wobj)
s = @epub.colophon
if !s.nil? && !wobj.nil?
wobj.puts s
end
end | ruby | def colophon(wobj)
s = @epub.colophon
if !s.nil? && !wobj.nil?
wobj.puts s
end
end | [
"def",
"colophon",
"(",
"wobj",
")",
"s",
"=",
"@epub",
".",
"colophon",
"if",
"!",
"s",
".",
"nil?",
"&&",
"!",
"wobj",
".",
"nil?",
"wobj",
".",
"puts",
"s",
"end",
"end"
] | Write colophon file to IO object +wobj+. | [
"Write",
"colophon",
"file",
"to",
"IO",
"object",
"+",
"wobj",
"+",
"."
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L150-L155 | train |
kmuto/review | lib/epubmaker/producer.rb | EPUBMaker.Producer.mytoc | def mytoc(wobj)
s = @epub.mytoc
if !s.nil? && !wobj.nil?
wobj.puts s
end
end | ruby | def mytoc(wobj)
s = @epub.mytoc
if !s.nil? && !wobj.nil?
wobj.puts s
end
end | [
"def",
"mytoc",
"(",
"wobj",
")",
"s",
"=",
"@epub",
".",
"mytoc",
"if",
"!",
"s",
".",
"nil?",
"&&",
"!",
"wobj",
".",
"nil?",
"wobj",
".",
"puts",
"s",
"end",
"end"
] | Write own toc file to IO object +wobj+. | [
"Write",
"own",
"toc",
"file",
"to",
"IO",
"object",
"+",
"wobj",
"+",
"."
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L158-L163 | train |
kmuto/review | lib/epubmaker/epubv2.rb | EPUBMaker.EPUBv2.ncx | def ncx(indentarray)
@ncx_isbn = ncx_isbn
@ncx_doctitle = ncx_doctitle
@ncx_navmap = ncx_navmap(indentarray)
tmplfile = File.expand_path('./ncx/epubv2.ncx.erb', ReVIEW::Template::TEMPLATE_DIR)
ReVIEW::Template.load(tmplfile).result(binding)
end | ruby | def ncx(indentarray)
@ncx_isbn = ncx_isbn
@ncx_doctitle = ncx_doctitle
@ncx_navmap = ncx_navmap(indentarray)
tmplfile = File.expand_path('./ncx/epubv2.ncx.erb', ReVIEW::Template::TEMPLATE_DIR)
ReVIEW::Template.load(tmplfile).result(binding)
end | [
"def",
"ncx",
"(",
"indentarray",
")",
"@ncx_isbn",
"=",
"ncx_isbn",
"@ncx_doctitle",
"=",
"ncx_doctitle",
"@ncx_navmap",
"=",
"ncx_navmap",
"(",
"indentarray",
")",
"tmplfile",
"=",
"File",
".",
"expand_path",
"(",
"'./ncx/epubv2.ncx.erb'",
",",
"ReVIEW",
"::",
"Template",
"::",
"TEMPLATE_DIR",
")",
"ReVIEW",
"::",
"Template",
".",
"load",
"(",
"tmplfile",
")",
".",
"result",
"(",
"binding",
")",
"end"
] | Return ncx content. +indentarray+ has prefix marks for each level. | [
"Return",
"ncx",
"content",
".",
"+",
"indentarray",
"+",
"has",
"prefix",
"marks",
"for",
"each",
"level",
"."
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/epubv2.rb#L114-L121 | train |
kmuto/review | lib/epubmaker/epubv2.rb | EPUBMaker.EPUBv2.produce | def produce(epubfile, basedir, tmpdir)
produce_write_common(basedir, tmpdir)
File.open("#{tmpdir}/OEBPS/#{@producer.config['bookname']}.ncx", 'w') do |f|
@producer.ncx(f, @producer.config['epubmaker']['ncxindent'])
end
if @producer.config['mytoc']
File.open("#{tmpdir}/OEBPS/#{@producer.config['bookname']}-toc.#{@producer.config['htmlext']}", 'w') do |f|
@producer.mytoc(f)
end
end
@producer.call_hook(@producer.config['epubmaker']['hook_prepack'], tmpdir)
expoter = EPUBMaker::ZipExporter.new(tmpdir, @producer.config)
expoter.export_zip(epubfile)
end | ruby | def produce(epubfile, basedir, tmpdir)
produce_write_common(basedir, tmpdir)
File.open("#{tmpdir}/OEBPS/#{@producer.config['bookname']}.ncx", 'w') do |f|
@producer.ncx(f, @producer.config['epubmaker']['ncxindent'])
end
if @producer.config['mytoc']
File.open("#{tmpdir}/OEBPS/#{@producer.config['bookname']}-toc.#{@producer.config['htmlext']}", 'w') do |f|
@producer.mytoc(f)
end
end
@producer.call_hook(@producer.config['epubmaker']['hook_prepack'], tmpdir)
expoter = EPUBMaker::ZipExporter.new(tmpdir, @producer.config)
expoter.export_zip(epubfile)
end | [
"def",
"produce",
"(",
"epubfile",
",",
"basedir",
",",
"tmpdir",
")",
"produce_write_common",
"(",
"basedir",
",",
"tmpdir",
")",
"File",
".",
"open",
"(",
"\"#{tmpdir}/OEBPS/#{@producer.config['bookname']}.ncx\"",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"@producer",
".",
"ncx",
"(",
"f",
",",
"@producer",
".",
"config",
"[",
"'epubmaker'",
"]",
"[",
"'ncxindent'",
"]",
")",
"end",
"if",
"@producer",
".",
"config",
"[",
"'mytoc'",
"]",
"File",
".",
"open",
"(",
"\"#{tmpdir}/OEBPS/#{@producer.config['bookname']}-toc.#{@producer.config['htmlext']}\"",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"@producer",
".",
"mytoc",
"(",
"f",
")",
"end",
"end",
"@producer",
".",
"call_hook",
"(",
"@producer",
".",
"config",
"[",
"'epubmaker'",
"]",
"[",
"'hook_prepack'",
"]",
",",
"tmpdir",
")",
"expoter",
"=",
"EPUBMaker",
"::",
"ZipExporter",
".",
"new",
"(",
"tmpdir",
",",
"@producer",
".",
"config",
")",
"expoter",
".",
"export_zip",
"(",
"epubfile",
")",
"end"
] | Produce EPUB file +epubfile+.
+basedir+ points the directory has contents.
+tmpdir+ defines temporary directory. | [
"Produce",
"EPUB",
"file",
"+",
"epubfile",
"+",
".",
"+",
"basedir",
"+",
"points",
"the",
"directory",
"has",
"contents",
".",
"+",
"tmpdir",
"+",
"defines",
"temporary",
"directory",
"."
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/epubv2.rb#L126-L141 | train |
kmuto/review | lib/review/latexbuilder.rb | ReVIEW.LATEXBuilder.inline_i | def inline_i(str)
if @book.config.check_version('2', exception: false)
macro('textit', escape(str))
else
macro('reviewit', escape(str))
end
end | ruby | def inline_i(str)
if @book.config.check_version('2', exception: false)
macro('textit', escape(str))
else
macro('reviewit', escape(str))
end
end | [
"def",
"inline_i",
"(",
"str",
")",
"if",
"@book",
".",
"config",
".",
"check_version",
"(",
"'2'",
",",
"exception",
":",
"false",
")",
"macro",
"(",
"'textit'",
",",
"escape",
"(",
"str",
")",
")",
"else",
"macro",
"(",
"'reviewit'",
",",
"escape",
"(",
"str",
")",
")",
"end",
"end"
] | index -> italic | [
"index",
"-",
">",
"italic"
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/review/latexbuilder.rb#L1022-L1028 | train |
kmuto/review | lib/review/yamlloader.rb | ReVIEW.YAMLLoader.load_file | def load_file(yamlfile)
file_queue = [File.expand_path(yamlfile)]
loaded_files = {}
yaml = {}
loop do
# Check exit condition
return yaml if file_queue.empty?
current_file = file_queue.shift
current_yaml = YAML.load_file(current_file)
yaml = current_yaml.deep_merge(yaml)
next unless yaml.key?('inherit')
buf = []
yaml['inherit'].reverse_each do |item|
inherit_file = File.expand_path(item, File.dirname(yamlfile))
# Check loop
if loaded_files[inherit_file]
raise "Found circular YAML inheritance '#{inherit_file}' in #{yamlfile}."
end
loaded_files[inherit_file] = true
buf << inherit_file
end
yaml.delete('inherit')
file_queue = buf + file_queue
end
end | ruby | def load_file(yamlfile)
file_queue = [File.expand_path(yamlfile)]
loaded_files = {}
yaml = {}
loop do
# Check exit condition
return yaml if file_queue.empty?
current_file = file_queue.shift
current_yaml = YAML.load_file(current_file)
yaml = current_yaml.deep_merge(yaml)
next unless yaml.key?('inherit')
buf = []
yaml['inherit'].reverse_each do |item|
inherit_file = File.expand_path(item, File.dirname(yamlfile))
# Check loop
if loaded_files[inherit_file]
raise "Found circular YAML inheritance '#{inherit_file}' in #{yamlfile}."
end
loaded_files[inherit_file] = true
buf << inherit_file
end
yaml.delete('inherit')
file_queue = buf + file_queue
end
end | [
"def",
"load_file",
"(",
"yamlfile",
")",
"file_queue",
"=",
"[",
"File",
".",
"expand_path",
"(",
"yamlfile",
")",
"]",
"loaded_files",
"=",
"{",
"}",
"yaml",
"=",
"{",
"}",
"loop",
"do",
"# Check exit condition",
"return",
"yaml",
"if",
"file_queue",
".",
"empty?",
"current_file",
"=",
"file_queue",
".",
"shift",
"current_yaml",
"=",
"YAML",
".",
"load_file",
"(",
"current_file",
")",
"yaml",
"=",
"current_yaml",
".",
"deep_merge",
"(",
"yaml",
")",
"next",
"unless",
"yaml",
".",
"key?",
"(",
"'inherit'",
")",
"buf",
"=",
"[",
"]",
"yaml",
"[",
"'inherit'",
"]",
".",
"reverse_each",
"do",
"|",
"item",
"|",
"inherit_file",
"=",
"File",
".",
"expand_path",
"(",
"item",
",",
"File",
".",
"dirname",
"(",
"yamlfile",
")",
")",
"# Check loop",
"if",
"loaded_files",
"[",
"inherit_file",
"]",
"raise",
"\"Found circular YAML inheritance '#{inherit_file}' in #{yamlfile}.\"",
"end",
"loaded_files",
"[",
"inherit_file",
"]",
"=",
"true",
"buf",
"<<",
"inherit_file",
"end",
"yaml",
".",
"delete",
"(",
"'inherit'",
")",
"file_queue",
"=",
"buf",
"+",
"file_queue",
"end",
"end"
] | load YAML files
`inherit: [3.yml, 6.yml]` in 7.yml; `inherit: [1.yml, 2.yml]` in 3.yml; `inherit: [4.yml, 5.yml]` in 6.yml
=> 7.yml > 6.yml > 5.yml > 4.yml > 3.yml > 2.yml > 1.yml | [
"load",
"YAML",
"files"
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/review/yamlloader.rb#L13-L43 | train |
kmuto/review | lib/epubmaker/content.rb | EPUBMaker.Content.complement | def complement
if @id.nil?
@id = @file.gsub(%r{[\\/\. ]}, '-')
end
if @id =~ /\A[^a-z]/i
@id = "rv-#{@id}"
end
if [email protected]? && @media.nil?
@media = @file.sub(/.+\./, '').downcase
end
case @media
when 'xhtml', 'xml', 'html'
@media = 'application/xhtml+xml'
when 'css'
@media = 'text/css'
when 'jpg', 'jpeg', 'image/jpg'
@media = 'image/jpeg'
when 'png'
@media = 'image/png'
when 'gif'
@media = 'image/gif'
when 'svg', 'image/svg'
@media = 'image/svg+xml'
when 'ttf', 'otf'
@media = 'application/vnd.ms-opentype'
when 'woff'
@media = 'application/font-woff'
end
if @id.nil? || @file.nil? || @media.nil?
raise "Type error: #{id}, #{file}, #{media}, #{title}, #{notoc}"
end
end | ruby | def complement
if @id.nil?
@id = @file.gsub(%r{[\\/\. ]}, '-')
end
if @id =~ /\A[^a-z]/i
@id = "rv-#{@id}"
end
if [email protected]? && @media.nil?
@media = @file.sub(/.+\./, '').downcase
end
case @media
when 'xhtml', 'xml', 'html'
@media = 'application/xhtml+xml'
when 'css'
@media = 'text/css'
when 'jpg', 'jpeg', 'image/jpg'
@media = 'image/jpeg'
when 'png'
@media = 'image/png'
when 'gif'
@media = 'image/gif'
when 'svg', 'image/svg'
@media = 'image/svg+xml'
when 'ttf', 'otf'
@media = 'application/vnd.ms-opentype'
when 'woff'
@media = 'application/font-woff'
end
if @id.nil? || @file.nil? || @media.nil?
raise "Type error: #{id}, #{file}, #{media}, #{title}, #{notoc}"
end
end | [
"def",
"complement",
"if",
"@id",
".",
"nil?",
"@id",
"=",
"@file",
".",
"gsub",
"(",
"%r{",
"\\\\",
"\\.",
"}",
",",
"'-'",
")",
"end",
"if",
"@id",
"=~",
"/",
"\\A",
"/i",
"@id",
"=",
"\"rv-#{@id}\"",
"end",
"if",
"!",
"@file",
".",
"nil?",
"&&",
"@media",
".",
"nil?",
"@media",
"=",
"@file",
".",
"sub",
"(",
"/",
"\\.",
"/",
",",
"''",
")",
".",
"downcase",
"end",
"case",
"@media",
"when",
"'xhtml'",
",",
"'xml'",
",",
"'html'",
"@media",
"=",
"'application/xhtml+xml'",
"when",
"'css'",
"@media",
"=",
"'text/css'",
"when",
"'jpg'",
",",
"'jpeg'",
",",
"'image/jpg'",
"@media",
"=",
"'image/jpeg'",
"when",
"'png'",
"@media",
"=",
"'image/png'",
"when",
"'gif'",
"@media",
"=",
"'image/gif'",
"when",
"'svg'",
",",
"'image/svg'",
"@media",
"=",
"'image/svg+xml'",
"when",
"'ttf'",
",",
"'otf'",
"@media",
"=",
"'application/vnd.ms-opentype'",
"when",
"'woff'",
"@media",
"=",
"'application/font-woff'",
"end",
"if",
"@id",
".",
"nil?",
"||",
"@file",
".",
"nil?",
"||",
"@media",
".",
"nil?",
"raise",
"\"Type error: #{id}, #{file}, #{media}, #{title}, #{notoc}\"",
"end",
"end"
] | Complement other parameters by using file parameter. | [
"Complement",
"other",
"parameters",
"by",
"using",
"file",
"parameter",
"."
] | 77d1273e671663f05db2992281fd891b776badf0 | https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/content.rb#L74-L108 | train |
splitrb/split | lib/split/trial.rb | Split.Trial.choose! | def choose!(context = nil)
@user.cleanup_old_experiments!
# Only run the process once
return alternative if @alternative_choosen
if override_is_alternative?
self.alternative = @options[:override]
if should_store_alternative? && !@user[@experiment.key]
self.alternative.increment_participation
end
elsif @options[:disabled] || Split.configuration.disabled?
self.alternative = @experiment.control
elsif @experiment.has_winner?
self.alternative = @experiment.winner
else
cleanup_old_versions
if exclude_user?
self.alternative = @experiment.control
else
self.alternative = @user[@experiment.key]
if alternative.nil?
self.alternative = @experiment.next_alternative
# Increment the number of participants since we are actually choosing a new alternative
self.alternative.increment_participation
run_callback context, Split.configuration.on_trial_choose
end
end
end
@user[@experiment.key] = alternative.name if [email protected]_winner? && should_store_alternative?
@alternative_choosen = true
run_callback context, Split.configuration.on_trial unless @options[:disabled] || Split.configuration.disabled?
alternative
end | ruby | def choose!(context = nil)
@user.cleanup_old_experiments!
# Only run the process once
return alternative if @alternative_choosen
if override_is_alternative?
self.alternative = @options[:override]
if should_store_alternative? && !@user[@experiment.key]
self.alternative.increment_participation
end
elsif @options[:disabled] || Split.configuration.disabled?
self.alternative = @experiment.control
elsif @experiment.has_winner?
self.alternative = @experiment.winner
else
cleanup_old_versions
if exclude_user?
self.alternative = @experiment.control
else
self.alternative = @user[@experiment.key]
if alternative.nil?
self.alternative = @experiment.next_alternative
# Increment the number of participants since we are actually choosing a new alternative
self.alternative.increment_participation
run_callback context, Split.configuration.on_trial_choose
end
end
end
@user[@experiment.key] = alternative.name if [email protected]_winner? && should_store_alternative?
@alternative_choosen = true
run_callback context, Split.configuration.on_trial unless @options[:disabled] || Split.configuration.disabled?
alternative
end | [
"def",
"choose!",
"(",
"context",
"=",
"nil",
")",
"@user",
".",
"cleanup_old_experiments!",
"# Only run the process once",
"return",
"alternative",
"if",
"@alternative_choosen",
"if",
"override_is_alternative?",
"self",
".",
"alternative",
"=",
"@options",
"[",
":override",
"]",
"if",
"should_store_alternative?",
"&&",
"!",
"@user",
"[",
"@experiment",
".",
"key",
"]",
"self",
".",
"alternative",
".",
"increment_participation",
"end",
"elsif",
"@options",
"[",
":disabled",
"]",
"||",
"Split",
".",
"configuration",
".",
"disabled?",
"self",
".",
"alternative",
"=",
"@experiment",
".",
"control",
"elsif",
"@experiment",
".",
"has_winner?",
"self",
".",
"alternative",
"=",
"@experiment",
".",
"winner",
"else",
"cleanup_old_versions",
"if",
"exclude_user?",
"self",
".",
"alternative",
"=",
"@experiment",
".",
"control",
"else",
"self",
".",
"alternative",
"=",
"@user",
"[",
"@experiment",
".",
"key",
"]",
"if",
"alternative",
".",
"nil?",
"self",
".",
"alternative",
"=",
"@experiment",
".",
"next_alternative",
"# Increment the number of participants since we are actually choosing a new alternative",
"self",
".",
"alternative",
".",
"increment_participation",
"run_callback",
"context",
",",
"Split",
".",
"configuration",
".",
"on_trial_choose",
"end",
"end",
"end",
"@user",
"[",
"@experiment",
".",
"key",
"]",
"=",
"alternative",
".",
"name",
"if",
"!",
"@experiment",
".",
"has_winner?",
"&&",
"should_store_alternative?",
"@alternative_choosen",
"=",
"true",
"run_callback",
"context",
",",
"Split",
".",
"configuration",
".",
"on_trial",
"unless",
"@options",
"[",
":disabled",
"]",
"||",
"Split",
".",
"configuration",
".",
"disabled?",
"alternative",
"end"
] | Choose an alternative, add a participant, and save the alternative choice on the user. This
method is guaranteed to only run once, and will skip the alternative choosing process if run
a second time. | [
"Choose",
"an",
"alternative",
"add",
"a",
"participant",
"and",
"save",
"the",
"alternative",
"choice",
"on",
"the",
"user",
".",
"This",
"method",
"is",
"guaranteed",
"to",
"only",
"run",
"once",
"and",
"will",
"skip",
"the",
"alternative",
"choosing",
"process",
"if",
"run",
"a",
"second",
"time",
"."
] | 02f3f14f99288c3395910999cdb657f2ec5a06cd | https://github.com/splitrb/split/blob/02f3f14f99288c3395910999cdb657f2ec5a06cd/lib/split/trial.rb#L51-L87 | train |
brianmario/mysql2 | lib/mysql2/client.rb | Mysql2.Client.parse_connect_attrs | def parse_connect_attrs(conn_attrs)
return {} if Mysql2::Client::CONNECT_ATTRS.zero?
conn_attrs ||= {}
conn_attrs[:program_name] ||= $PROGRAM_NAME
conn_attrs.each_with_object({}) do |(key, value), hash|
hash[key.to_s] = value.to_s
end
end | ruby | def parse_connect_attrs(conn_attrs)
return {} if Mysql2::Client::CONNECT_ATTRS.zero?
conn_attrs ||= {}
conn_attrs[:program_name] ||= $PROGRAM_NAME
conn_attrs.each_with_object({}) do |(key, value), hash|
hash[key.to_s] = value.to_s
end
end | [
"def",
"parse_connect_attrs",
"(",
"conn_attrs",
")",
"return",
"{",
"}",
"if",
"Mysql2",
"::",
"Client",
"::",
"CONNECT_ATTRS",
".",
"zero?",
"conn_attrs",
"||=",
"{",
"}",
"conn_attrs",
"[",
":program_name",
"]",
"||=",
"$PROGRAM_NAME",
"conn_attrs",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"key",
",",
"value",
")",
",",
"hash",
"|",
"hash",
"[",
"key",
".",
"to_s",
"]",
"=",
"value",
".",
"to_s",
"end",
"end"
] | Set default program_name in performance_schema.session_connect_attrs
and performance_schema.session_account_connect_attrs | [
"Set",
"default",
"program_name",
"in",
"performance_schema",
".",
"session_connect_attrs",
"and",
"performance_schema",
".",
"session_account_connect_attrs"
] | c8c346db72b5505740065d9de79b4a52081d5a57 | https://github.com/brianmario/mysql2/blob/c8c346db72b5505740065d9de79b4a52081d5a57/lib/mysql2/client.rb#L120-L127 | train |
brianmario/mysql2 | lib/mysql2/error.rb | Mysql2.Error.clean_message | def clean_message(message)
if @server_version && @server_version > 50500
message.encode(ENCODE_OPTS)
else
message.encode(Encoding::UTF_8, ENCODE_OPTS)
end
end | ruby | def clean_message(message)
if @server_version && @server_version > 50500
message.encode(ENCODE_OPTS)
else
message.encode(Encoding::UTF_8, ENCODE_OPTS)
end
end | [
"def",
"clean_message",
"(",
"message",
")",
"if",
"@server_version",
"&&",
"@server_version",
">",
"50500",
"message",
".",
"encode",
"(",
"ENCODE_OPTS",
")",
"else",
"message",
".",
"encode",
"(",
"Encoding",
"::",
"UTF_8",
",",
"ENCODE_OPTS",
")",
"end",
"end"
] | In MySQL 5.5+ error messages are always constructed server-side as UTF-8
then returned in the encoding set by the `character_set_results` system
variable.
See http://dev.mysql.com/doc/refman/5.5/en/charset-errors.html for
more context.
Before MySQL 5.5 error message template strings are in whatever encoding
is associated with the error message language.
See http://dev.mysql.com/doc/refman/5.1/en/error-message-language.html
for more information.
The issue is that the user-data inserted in the message could potentially
be in any encoding MySQL supports and is insert into the latin1, euckr or
koi8r string raw. Meaning there's a high probability the string will be
corrupt encoding-wise.
See http://dev.mysql.com/doc/refman/5.1/en/charset-errors.html for
more information.
So in an attempt to make sure the error message string is always in a valid
encoding, we'll assume UTF-8 and clean the string of anything that's not a
valid UTF-8 character.
Returns a valid UTF-8 string. | [
"In",
"MySQL",
"5",
".",
"5",
"+",
"error",
"messages",
"are",
"always",
"constructed",
"server",
"-",
"side",
"as",
"UTF",
"-",
"8",
"then",
"returned",
"in",
"the",
"encoding",
"set",
"by",
"the",
"character_set_results",
"system",
"variable",
"."
] | c8c346db72b5505740065d9de79b4a52081d5a57 | https://github.com/brianmario/mysql2/blob/c8c346db72b5505740065d9de79b4a52081d5a57/lib/mysql2/error.rb#L92-L98 | train |
zipmark/rspec_api_documentation | lib/rspec_api_documentation/dsl.rb | RspecApiDocumentation.DSL.resource | def resource(*args, &block)
options = args.last.is_a?(Hash) ? args.pop : {}
options[:api_doc_dsl] = :resource
options[:resource_name] = args.first.to_s
options[:document] = :all unless options.key?(:document)
args.push(options)
describe(*args, &block)
end | ruby | def resource(*args, &block)
options = args.last.is_a?(Hash) ? args.pop : {}
options[:api_doc_dsl] = :resource
options[:resource_name] = args.first.to_s
options[:document] = :all unless options.key?(:document)
args.push(options)
describe(*args, &block)
end | [
"def",
"resource",
"(",
"*",
"args",
",",
"&",
"block",
")",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"options",
"[",
":api_doc_dsl",
"]",
"=",
":resource",
"options",
"[",
":resource_name",
"]",
"=",
"args",
".",
"first",
".",
"to_s",
"options",
"[",
":document",
"]",
"=",
":all",
"unless",
"options",
".",
"key?",
"(",
":document",
")",
"args",
".",
"push",
"(",
"options",
")",
"describe",
"(",
"args",
",",
"block",
")",
"end"
] | Custom describe block that sets metadata to enable the rest of RAD
resource "Orders", :meta => :data do
# ...
end
Params:
+args+:: Glob of RSpec's `describe` arguments
+block+:: Block to pass into describe | [
"Custom",
"describe",
"block",
"that",
"sets",
"metadata",
"to",
"enable",
"the",
"rest",
"of",
"RAD"
] | 54fbfda3ec8ede5b3d871700ff69aabe89eafb2f | https://github.com/zipmark/rspec_api_documentation/blob/54fbfda3ec8ede5b3d871700ff69aabe89eafb2f/lib/rspec_api_documentation/dsl.rb#L20-L27 | train |
zipmark/rspec_api_documentation | lib/rspec_api_documentation/configuration.rb | RspecApiDocumentation.Configuration.define_group | def define_group(name, &block)
subconfig = self.class.new(self)
subconfig.filter = name
subconfig.docs_dir = self.docs_dir.join(name.to_s)
yield subconfig
groups << subconfig
end | ruby | def define_group(name, &block)
subconfig = self.class.new(self)
subconfig.filter = name
subconfig.docs_dir = self.docs_dir.join(name.to_s)
yield subconfig
groups << subconfig
end | [
"def",
"define_group",
"(",
"name",
",",
"&",
"block",
")",
"subconfig",
"=",
"self",
".",
"class",
".",
"new",
"(",
"self",
")",
"subconfig",
".",
"filter",
"=",
"name",
"subconfig",
".",
"docs_dir",
"=",
"self",
".",
"docs_dir",
".",
"join",
"(",
"name",
".",
"to_s",
")",
"yield",
"subconfig",
"groups",
"<<",
"subconfig",
"end"
] | Defines a new sub configuration
Automatically sets the `filter` to the group name, and the `docs_dir` to
a subfolder of the parent's `doc_dir` named the group name.
RspecApiDocumentation.configure do |config|
config.docs_dir = "doc/api"
config.define_group(:public) do |config|
# Default values
config.docs_dir = "doc/api/public"
config.filter = :public
end
end
Params:
+name+:: String name of the group
+block+:: Block configuration block | [
"Defines",
"a",
"new",
"sub",
"configuration"
] | 54fbfda3ec8ede5b3d871700ff69aabe89eafb2f | https://github.com/zipmark/rspec_api_documentation/blob/54fbfda3ec8ede5b3d871700ff69aabe89eafb2f/lib/rspec_api_documentation/configuration.rb#L33-L39 | train |
brunofacca/active-record-query-trace | lib/active_record_query_trace.rb | ActiveRecordQueryTrace.CustomLogSubscriber.lines_to_display | def lines_to_display(full_trace)
ActiveRecordQueryTrace.lines.zero? ? full_trace : full_trace.first(ActiveRecordQueryTrace.lines)
end | ruby | def lines_to_display(full_trace)
ActiveRecordQueryTrace.lines.zero? ? full_trace : full_trace.first(ActiveRecordQueryTrace.lines)
end | [
"def",
"lines_to_display",
"(",
"full_trace",
")",
"ActiveRecordQueryTrace",
".",
"lines",
".",
"zero?",
"?",
"full_trace",
":",
"full_trace",
".",
"first",
"(",
"ActiveRecordQueryTrace",
".",
"lines",
")",
"end"
] | Must be called after the backtrace cleaner. | [
"Must",
"be",
"called",
"after",
"the",
"backtrace",
"cleaner",
"."
] | 9584d5d49cfc2170271f75bbf2773b46145e1be4 | https://github.com/brunofacca/active-record-query-trace/blob/9584d5d49cfc2170271f75bbf2773b46145e1be4/lib/active_record_query_trace.rb#L101-L103 | train |
brunofacca/active-record-query-trace | lib/active_record_query_trace.rb | ActiveRecordQueryTrace.CustomLogSubscriber.setup_backtrace_cleaner_path | def setup_backtrace_cleaner_path
return unless Rails.backtrace_cleaner.instance_variable_get(:@root) == '/'
Rails.backtrace_cleaner.instance_variable_set :@root, Rails.root.to_s
end | ruby | def setup_backtrace_cleaner_path
return unless Rails.backtrace_cleaner.instance_variable_get(:@root) == '/'
Rails.backtrace_cleaner.instance_variable_set :@root, Rails.root.to_s
end | [
"def",
"setup_backtrace_cleaner_path",
"return",
"unless",
"Rails",
".",
"backtrace_cleaner",
".",
"instance_variable_get",
"(",
":@root",
")",
"==",
"'/'",
"Rails",
".",
"backtrace_cleaner",
".",
"instance_variable_set",
":@root",
",",
"Rails",
".",
"root",
".",
"to_s",
"end"
] | Rails relies on backtrace cleaner to set the application root directory
filter. The problem is that the backtrace cleaner is initialized before
this gem. This ensures that the value of `root` used by the filter
is correct. | [
"Rails",
"relies",
"on",
"backtrace",
"cleaner",
"to",
"set",
"the",
"application",
"root",
"directory",
"filter",
".",
"The",
"problem",
"is",
"that",
"the",
"backtrace",
"cleaner",
"is",
"initialized",
"before",
"this",
"gem",
".",
"This",
"ensures",
"that",
"the",
"value",
"of",
"root",
"used",
"by",
"the",
"filter",
"is",
"correct",
"."
] | 9584d5d49cfc2170271f75bbf2773b46145e1be4 | https://github.com/brunofacca/active-record-query-trace/blob/9584d5d49cfc2170271f75bbf2773b46145e1be4/lib/active_record_query_trace.rb#L152-L155 | train |
stripe/stripe-ruby | lib/stripe/stripe_object.rb | Stripe.StripeObject.update_attributes | def update_attributes(values, opts = {}, dirty: true)
values.each do |k, v|
add_accessors([k], values) unless metaclass.method_defined?(k.to_sym)
@values[k] = Util.convert_to_stripe_object(v, opts)
dirty_value!(@values[k]) if dirty
@unsaved_values.add(k)
end
end | ruby | def update_attributes(values, opts = {}, dirty: true)
values.each do |k, v|
add_accessors([k], values) unless metaclass.method_defined?(k.to_sym)
@values[k] = Util.convert_to_stripe_object(v, opts)
dirty_value!(@values[k]) if dirty
@unsaved_values.add(k)
end
end | [
"def",
"update_attributes",
"(",
"values",
",",
"opts",
"=",
"{",
"}",
",",
"dirty",
":",
"true",
")",
"values",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"add_accessors",
"(",
"[",
"k",
"]",
",",
"values",
")",
"unless",
"metaclass",
".",
"method_defined?",
"(",
"k",
".",
"to_sym",
")",
"@values",
"[",
"k",
"]",
"=",
"Util",
".",
"convert_to_stripe_object",
"(",
"v",
",",
"opts",
")",
"dirty_value!",
"(",
"@values",
"[",
"k",
"]",
")",
"if",
"dirty",
"@unsaved_values",
".",
"add",
"(",
"k",
")",
"end",
"end"
] | Mass assigns attributes on the model.
This is a version of +update_attributes+ that takes some extra options
for internal use.
==== Attributes
* +values+ - Hash of values to use to update the current attributes of
the object.
* +opts+ - Options for +StripeObject+ like an API key that will be reused
on subsequent API calls.
==== Options
* +:dirty+ - Whether values should be initiated as "dirty" (unsaved) and
which applies only to new StripeObjects being initiated under this
StripeObject. Defaults to true. | [
"Mass",
"assigns",
"attributes",
"on",
"the",
"model",
"."
] | 322a8c60be8a9b9ac8aad8857864680a32176935 | https://github.com/stripe/stripe-ruby/blob/322a8c60be8a9b9ac8aad8857864680a32176935/lib/stripe/stripe_object.rb#L156-L163 | train |
stripe/stripe-ruby | lib/stripe/stripe_object.rb | Stripe.StripeObject.empty_values | def empty_values(obj)
values = case obj
when Hash then obj
when StripeObject then obj.instance_variable_get(:@values)
else
raise ArgumentError, "#empty_values got unexpected object type: #{obj.class.name}"
end
values.each_with_object({}) do |(k, _), update|
update[k] = ""
end
end | ruby | def empty_values(obj)
values = case obj
when Hash then obj
when StripeObject then obj.instance_variable_get(:@values)
else
raise ArgumentError, "#empty_values got unexpected object type: #{obj.class.name}"
end
values.each_with_object({}) do |(k, _), update|
update[k] = ""
end
end | [
"def",
"empty_values",
"(",
"obj",
")",
"values",
"=",
"case",
"obj",
"when",
"Hash",
"then",
"obj",
"when",
"StripeObject",
"then",
"obj",
".",
"instance_variable_get",
"(",
":@values",
")",
"else",
"raise",
"ArgumentError",
",",
"\"#empty_values got unexpected object type: #{obj.class.name}\"",
"end",
"values",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"k",
",",
"_",
")",
",",
"update",
"|",
"update",
"[",
"k",
"]",
"=",
"\"\"",
"end",
"end"
] | Returns a hash of empty values for all the values that are in the given
StripeObject. | [
"Returns",
"a",
"hash",
"of",
"empty",
"values",
"for",
"all",
"the",
"values",
"that",
"are",
"in",
"the",
"given",
"StripeObject",
"."
] | 322a8c60be8a9b9ac8aad8857864680a32176935 | https://github.com/stripe/stripe-ruby/blob/322a8c60be8a9b9ac8aad8857864680a32176935/lib/stripe/stripe_object.rb#L556-L567 | train |
stripe/stripe-ruby | lib/stripe/list_object.rb | Stripe.ListObject.auto_paging_each | def auto_paging_each(&blk)
return enum_for(:auto_paging_each) unless block_given?
page = self
loop do
page.each(&blk)
page = page.next_page
break if page.empty?
end
end | ruby | def auto_paging_each(&blk)
return enum_for(:auto_paging_each) unless block_given?
page = self
loop do
page.each(&blk)
page = page.next_page
break if page.empty?
end
end | [
"def",
"auto_paging_each",
"(",
"&",
"blk",
")",
"return",
"enum_for",
"(",
":auto_paging_each",
")",
"unless",
"block_given?",
"page",
"=",
"self",
"loop",
"do",
"page",
".",
"each",
"(",
"blk",
")",
"page",
"=",
"page",
".",
"next_page",
"break",
"if",
"page",
".",
"empty?",
"end",
"end"
] | Iterates through each resource in all pages, making additional fetches to
the API as necessary.
Note that this method will make as many API calls as necessary to fetch
all resources. For more granular control, please see +each+ and
+next_page+. | [
"Iterates",
"through",
"each",
"resource",
"in",
"all",
"pages",
"making",
"additional",
"fetches",
"to",
"the",
"API",
"as",
"necessary",
"."
] | 322a8c60be8a9b9ac8aad8857864680a32176935 | https://github.com/stripe/stripe-ruby/blob/322a8c60be8a9b9ac8aad8857864680a32176935/lib/stripe/list_object.rb#L53-L62 | train |
stripe/stripe-ruby | lib/stripe/stripe_client.rb | Stripe.StripeClient.format_app_info | def format_app_info(info)
str = info[:name]
str = "#{str}/#{info[:version]}" unless info[:version].nil?
str = "#{str} (#{info[:url]})" unless info[:url].nil?
str
end | ruby | def format_app_info(info)
str = info[:name]
str = "#{str}/#{info[:version]}" unless info[:version].nil?
str = "#{str} (#{info[:url]})" unless info[:url].nil?
str
end | [
"def",
"format_app_info",
"(",
"info",
")",
"str",
"=",
"info",
"[",
":name",
"]",
"str",
"=",
"\"#{str}/#{info[:version]}\"",
"unless",
"info",
"[",
":version",
"]",
".",
"nil?",
"str",
"=",
"\"#{str} (#{info[:url]})\"",
"unless",
"info",
"[",
":url",
"]",
".",
"nil?",
"str",
"end"
] | Formats a plugin "app info" hash into a string that we can tack onto the
end of a User-Agent string where it'll be fairly prominent in places like
the Dashboard. Note that this formatting has been implemented to match
other libraries, and shouldn't be changed without universal consensus. | [
"Formats",
"a",
"plugin",
"app",
"info",
"hash",
"into",
"a",
"string",
"that",
"we",
"can",
"tack",
"onto",
"the",
"end",
"of",
"a",
"User",
"-",
"Agent",
"string",
"where",
"it",
"ll",
"be",
"fairly",
"prominent",
"in",
"places",
"like",
"the",
"Dashboard",
".",
"Note",
"that",
"this",
"formatting",
"has",
"been",
"implemented",
"to",
"match",
"other",
"libraries",
"and",
"shouldn",
"t",
"be",
"changed",
"without",
"universal",
"consensus",
"."
] | 322a8c60be8a9b9ac8aad8857864680a32176935 | https://github.com/stripe/stripe-ruby/blob/322a8c60be8a9b9ac8aad8857864680a32176935/lib/stripe/stripe_client.rb#L319-L324 | train |
stripe/stripe-ruby | lib/stripe/stripe_client.rb | Stripe.StripeClient.specific_oauth_error | def specific_oauth_error(resp, error_code, context)
description = resp.data[:error_description] || error_code
Util.log_error("Stripe OAuth error",
status: resp.http_status,
error_code: error_code,
error_description: description,
idempotency_key: context.idempotency_key,
request_id: context.request_id)
args = [error_code, description, {
http_status: resp.http_status, http_body: resp.http_body,
json_body: resp.data, http_headers: resp.http_headers,
},]
case error_code
when "invalid_client" then OAuth::InvalidClientError.new(*args)
when "invalid_grant" then OAuth::InvalidGrantError.new(*args)
when "invalid_request" then OAuth::InvalidRequestError.new(*args)
when "invalid_scope" then OAuth::InvalidScopeError.new(*args)
when "unsupported_grant_type" then OAuth::UnsupportedGrantTypeError.new(*args)
when "unsupported_response_type" then OAuth::UnsupportedResponseTypeError.new(*args)
else
# We'd prefer that all errors are typed, but we create a generic
# OAuthError in case we run into a code that we don't recognize.
OAuth::OAuthError.new(*args)
end
end | ruby | def specific_oauth_error(resp, error_code, context)
description = resp.data[:error_description] || error_code
Util.log_error("Stripe OAuth error",
status: resp.http_status,
error_code: error_code,
error_description: description,
idempotency_key: context.idempotency_key,
request_id: context.request_id)
args = [error_code, description, {
http_status: resp.http_status, http_body: resp.http_body,
json_body: resp.data, http_headers: resp.http_headers,
},]
case error_code
when "invalid_client" then OAuth::InvalidClientError.new(*args)
when "invalid_grant" then OAuth::InvalidGrantError.new(*args)
when "invalid_request" then OAuth::InvalidRequestError.new(*args)
when "invalid_scope" then OAuth::InvalidScopeError.new(*args)
when "unsupported_grant_type" then OAuth::UnsupportedGrantTypeError.new(*args)
when "unsupported_response_type" then OAuth::UnsupportedResponseTypeError.new(*args)
else
# We'd prefer that all errors are typed, but we create a generic
# OAuthError in case we run into a code that we don't recognize.
OAuth::OAuthError.new(*args)
end
end | [
"def",
"specific_oauth_error",
"(",
"resp",
",",
"error_code",
",",
"context",
")",
"description",
"=",
"resp",
".",
"data",
"[",
":error_description",
"]",
"||",
"error_code",
"Util",
".",
"log_error",
"(",
"\"Stripe OAuth error\"",
",",
"status",
":",
"resp",
".",
"http_status",
",",
"error_code",
":",
"error_code",
",",
"error_description",
":",
"description",
",",
"idempotency_key",
":",
"context",
".",
"idempotency_key",
",",
"request_id",
":",
"context",
".",
"request_id",
")",
"args",
"=",
"[",
"error_code",
",",
"description",
",",
"{",
"http_status",
":",
"resp",
".",
"http_status",
",",
"http_body",
":",
"resp",
".",
"http_body",
",",
"json_body",
":",
"resp",
".",
"data",
",",
"http_headers",
":",
"resp",
".",
"http_headers",
",",
"}",
",",
"]",
"case",
"error_code",
"when",
"\"invalid_client\"",
"then",
"OAuth",
"::",
"InvalidClientError",
".",
"new",
"(",
"args",
")",
"when",
"\"invalid_grant\"",
"then",
"OAuth",
"::",
"InvalidGrantError",
".",
"new",
"(",
"args",
")",
"when",
"\"invalid_request\"",
"then",
"OAuth",
"::",
"InvalidRequestError",
".",
"new",
"(",
"args",
")",
"when",
"\"invalid_scope\"",
"then",
"OAuth",
"::",
"InvalidScopeError",
".",
"new",
"(",
"args",
")",
"when",
"\"unsupported_grant_type\"",
"then",
"OAuth",
"::",
"UnsupportedGrantTypeError",
".",
"new",
"(",
"args",
")",
"when",
"\"unsupported_response_type\"",
"then",
"OAuth",
"::",
"UnsupportedResponseTypeError",
".",
"new",
"(",
"args",
")",
"else",
"# We'd prefer that all errors are typed, but we create a generic",
"# OAuthError in case we run into a code that we don't recognize.",
"OAuth",
"::",
"OAuthError",
".",
"new",
"(",
"args",
")",
"end",
"end"
] | Attempts to look at a response's error code and return an OAuth error if
one matches. Will return `nil` if the code isn't recognized. | [
"Attempts",
"to",
"look",
"at",
"a",
"response",
"s",
"error",
"code",
"and",
"return",
"an",
"OAuth",
"error",
"if",
"one",
"matches",
".",
"Will",
"return",
"nil",
"if",
"the",
"code",
"isn",
"t",
"recognized",
"."
] | 322a8c60be8a9b9ac8aad8857864680a32176935 | https://github.com/stripe/stripe-ruby/blob/322a8c60be8a9b9ac8aad8857864680a32176935/lib/stripe/stripe_client.rb#L398-L425 | train |
awesome-print/awesome_print | lib/awesome_print/ext/active_record.rb | AwesomePrint.ActiveRecord.awesome_active_record_instance | def awesome_active_record_instance(object)
return object.inspect if !defined?(::ActiveSupport::OrderedHash)
return awesome_object(object) if @options[:raw]
data = if object.class.column_names != object.attributes.keys
object.attributes
else
object.class.column_names.inject(::ActiveSupport::OrderedHash.new) do |hash, name|
if object.has_attribute?(name) || object.new_record?
value = object.respond_to?(name) ? object.send(name) : object.read_attribute(name)
hash[name.to_sym] = value
end
hash
end
end
"#{object} " << awesome_hash(data)
end | ruby | def awesome_active_record_instance(object)
return object.inspect if !defined?(::ActiveSupport::OrderedHash)
return awesome_object(object) if @options[:raw]
data = if object.class.column_names != object.attributes.keys
object.attributes
else
object.class.column_names.inject(::ActiveSupport::OrderedHash.new) do |hash, name|
if object.has_attribute?(name) || object.new_record?
value = object.respond_to?(name) ? object.send(name) : object.read_attribute(name)
hash[name.to_sym] = value
end
hash
end
end
"#{object} " << awesome_hash(data)
end | [
"def",
"awesome_active_record_instance",
"(",
"object",
")",
"return",
"object",
".",
"inspect",
"if",
"!",
"defined?",
"(",
"::",
"ActiveSupport",
"::",
"OrderedHash",
")",
"return",
"awesome_object",
"(",
"object",
")",
"if",
"@options",
"[",
":raw",
"]",
"data",
"=",
"if",
"object",
".",
"class",
".",
"column_names",
"!=",
"object",
".",
"attributes",
".",
"keys",
"object",
".",
"attributes",
"else",
"object",
".",
"class",
".",
"column_names",
".",
"inject",
"(",
"::",
"ActiveSupport",
"::",
"OrderedHash",
".",
"new",
")",
"do",
"|",
"hash",
",",
"name",
"|",
"if",
"object",
".",
"has_attribute?",
"(",
"name",
")",
"||",
"object",
".",
"new_record?",
"value",
"=",
"object",
".",
"respond_to?",
"(",
"name",
")",
"?",
"object",
".",
"send",
"(",
"name",
")",
":",
"object",
".",
"read_attribute",
"(",
"name",
")",
"hash",
"[",
"name",
".",
"to_sym",
"]",
"=",
"value",
"end",
"hash",
"end",
"end",
"\"#{object} \"",
"<<",
"awesome_hash",
"(",
"data",
")",
"end"
] | Format ActiveRecord instance object.
NOTE: by default only instance attributes (i.e. columns) are shown. To format
ActiveRecord instance as regular object showing its instance variables and
accessors use :raw => true option:
ap record, :raw => true
------------------------------------------------------------------------------ | [
"Format",
"ActiveRecord",
"instance",
"object",
"."
] | 4564fd74721562cbef2443f7d97109bf9192343d | https://github.com/awesome-print/awesome_print/blob/4564fd74721562cbef2443f7d97109bf9192343d/lib/awesome_print/ext/active_record.rb#L43-L59 | train |
awesome-print/awesome_print | lib/awesome_print/ext/ripple.rb | AwesomePrint.Ripple.awesome_ripple_document_instance | def awesome_ripple_document_instance(object)
return object.inspect if !defined?(::ActiveSupport::OrderedHash)
return awesome_object(object) if @options[:raw]
exclude_assoc = @options[:exclude_assoc] or @options[:exclude_associations]
data = object.attributes.inject(::ActiveSupport::OrderedHash.new) do |hash, (name, value)|
hash[name.to_sym] = object.send(name)
hash
end
unless exclude_assoc
data = object.class.embedded_associations.inject(data) do |hash, assoc|
hash[assoc.name] = object.get_proxy(assoc) # Should always be array or Ripple::EmbeddedDocument for embedded associations
hash
end
end
"#{object} " << awesome_hash(data)
end | ruby | def awesome_ripple_document_instance(object)
return object.inspect if !defined?(::ActiveSupport::OrderedHash)
return awesome_object(object) if @options[:raw]
exclude_assoc = @options[:exclude_assoc] or @options[:exclude_associations]
data = object.attributes.inject(::ActiveSupport::OrderedHash.new) do |hash, (name, value)|
hash[name.to_sym] = object.send(name)
hash
end
unless exclude_assoc
data = object.class.embedded_associations.inject(data) do |hash, assoc|
hash[assoc.name] = object.get_proxy(assoc) # Should always be array or Ripple::EmbeddedDocument for embedded associations
hash
end
end
"#{object} " << awesome_hash(data)
end | [
"def",
"awesome_ripple_document_instance",
"(",
"object",
")",
"return",
"object",
".",
"inspect",
"if",
"!",
"defined?",
"(",
"::",
"ActiveSupport",
"::",
"OrderedHash",
")",
"return",
"awesome_object",
"(",
"object",
")",
"if",
"@options",
"[",
":raw",
"]",
"exclude_assoc",
"=",
"@options",
"[",
":exclude_assoc",
"]",
"or",
"@options",
"[",
":exclude_associations",
"]",
"data",
"=",
"object",
".",
"attributes",
".",
"inject",
"(",
"::",
"ActiveSupport",
"::",
"OrderedHash",
".",
"new",
")",
"do",
"|",
"hash",
",",
"(",
"name",
",",
"value",
")",
"|",
"hash",
"[",
"name",
".",
"to_sym",
"]",
"=",
"object",
".",
"send",
"(",
"name",
")",
"hash",
"end",
"unless",
"exclude_assoc",
"data",
"=",
"object",
".",
"class",
".",
"embedded_associations",
".",
"inject",
"(",
"data",
")",
"do",
"|",
"hash",
",",
"assoc",
"|",
"hash",
"[",
"assoc",
".",
"name",
"]",
"=",
"object",
".",
"get_proxy",
"(",
"assoc",
")",
"# Should always be array or Ripple::EmbeddedDocument for embedded associations",
"hash",
"end",
"end",
"\"#{object} \"",
"<<",
"awesome_hash",
"(",
"data",
")",
"end"
] | Format Ripple instance object.
NOTE: by default only instance attributes are shown. To format a Ripple document instance
as a regular object showing its instance variables and accessors use :raw => true option:
ap document, :raw => true
------------------------------------------------------------------------------ | [
"Format",
"Ripple",
"instance",
"object",
"."
] | 4564fd74721562cbef2443f7d97109bf9192343d | https://github.com/awesome-print/awesome_print/blob/4564fd74721562cbef2443f7d97109bf9192343d/lib/awesome_print/ext/ripple.rb#L38-L56 | train |
awesome-print/awesome_print | lib/awesome_print/ext/mongo_mapper.rb | AwesomePrint.MongoMapper.awesome_mongo_mapper_instance | def awesome_mongo_mapper_instance(object)
return object.inspect if !defined?(::ActiveSupport::OrderedHash)
return awesome_object(object) if @options[:raw]
data = object.keys.keys.sort_by { |k| k }.inject(::ActiveSupport::OrderedHash.new) do |hash, name|
hash[name] = object[name]
hash
end
# Add in associations
if @options[:mongo_mapper][:show_associations]
object.associations.each do |name, assoc|
data[name.to_s] = if @options[:mongo_mapper][:inline_embedded] and assoc.embeddable?
object.send(name)
else
assoc
end
end
end
label = object.to_s
label = "#{colorize('embedded', :assoc)} #{label}" if object.is_a?(::MongoMapper::EmbeddedDocument)
"#{label} " << awesome_hash(data)
end | ruby | def awesome_mongo_mapper_instance(object)
return object.inspect if !defined?(::ActiveSupport::OrderedHash)
return awesome_object(object) if @options[:raw]
data = object.keys.keys.sort_by { |k| k }.inject(::ActiveSupport::OrderedHash.new) do |hash, name|
hash[name] = object[name]
hash
end
# Add in associations
if @options[:mongo_mapper][:show_associations]
object.associations.each do |name, assoc|
data[name.to_s] = if @options[:mongo_mapper][:inline_embedded] and assoc.embeddable?
object.send(name)
else
assoc
end
end
end
label = object.to_s
label = "#{colorize('embedded', :assoc)} #{label}" if object.is_a?(::MongoMapper::EmbeddedDocument)
"#{label} " << awesome_hash(data)
end | [
"def",
"awesome_mongo_mapper_instance",
"(",
"object",
")",
"return",
"object",
".",
"inspect",
"if",
"!",
"defined?",
"(",
"::",
"ActiveSupport",
"::",
"OrderedHash",
")",
"return",
"awesome_object",
"(",
"object",
")",
"if",
"@options",
"[",
":raw",
"]",
"data",
"=",
"object",
".",
"keys",
".",
"keys",
".",
"sort_by",
"{",
"|",
"k",
"|",
"k",
"}",
".",
"inject",
"(",
"::",
"ActiveSupport",
"::",
"OrderedHash",
".",
"new",
")",
"do",
"|",
"hash",
",",
"name",
"|",
"hash",
"[",
"name",
"]",
"=",
"object",
"[",
"name",
"]",
"hash",
"end",
"# Add in associations",
"if",
"@options",
"[",
":mongo_mapper",
"]",
"[",
":show_associations",
"]",
"object",
".",
"associations",
".",
"each",
"do",
"|",
"name",
",",
"assoc",
"|",
"data",
"[",
"name",
".",
"to_s",
"]",
"=",
"if",
"@options",
"[",
":mongo_mapper",
"]",
"[",
":inline_embedded",
"]",
"and",
"assoc",
".",
"embeddable?",
"object",
".",
"send",
"(",
"name",
")",
"else",
"assoc",
"end",
"end",
"end",
"label",
"=",
"object",
".",
"to_s",
"label",
"=",
"\"#{colorize('embedded', :assoc)} #{label}\"",
"if",
"object",
".",
"is_a?",
"(",
"::",
"MongoMapper",
"::",
"EmbeddedDocument",
")",
"\"#{label} \"",
"<<",
"awesome_hash",
"(",
"data",
")",
"end"
] | Format MongoMapper instance object.
NOTE: by default only instance attributes (i.e. keys) are shown. To format
MongoMapper instance as regular object showing its instance variables and
accessors use :raw => true option:
ap record, :raw => true
------------------------------------------------------------------------------ | [
"Format",
"MongoMapper",
"instance",
"object",
"."
] | 4564fd74721562cbef2443f7d97109bf9192343d | https://github.com/awesome-print/awesome_print/blob/4564fd74721562cbef2443f7d97109bf9192343d/lib/awesome_print/ext/mongo_mapper.rb#L67-L91 | train |
awesome-print/awesome_print | lib/awesome_print/ext/action_view.rb | AwesomePrint.ActionView.ap_debug | def ap_debug(object, options = {})
object.ai(
options.merge(html: true)
).sub(
/^<pre([\s>])/,
'<pre class="debug_dump"\\1'
)
end | ruby | def ap_debug(object, options = {})
object.ai(
options.merge(html: true)
).sub(
/^<pre([\s>])/,
'<pre class="debug_dump"\\1'
)
end | [
"def",
"ap_debug",
"(",
"object",
",",
"options",
"=",
"{",
"}",
")",
"object",
".",
"ai",
"(",
"options",
".",
"merge",
"(",
"html",
":",
"true",
")",
")",
".",
"sub",
"(",
"/",
"\\s",
"/",
",",
"'<pre class=\"debug_dump\"\\\\1'",
")",
"end"
] | Use HTML colors and add default "debug_dump" class to the resulting HTML. | [
"Use",
"HTML",
"colors",
"and",
"add",
"default",
"debug_dump",
"class",
"to",
"the",
"resulting",
"HTML",
"."
] | 4564fd74721562cbef2443f7d97109bf9192343d | https://github.com/awesome-print/awesome_print/blob/4564fd74721562cbef2443f7d97109bf9192343d/lib/awesome_print/ext/action_view.rb#L9-L16 | train |
comfy/comfortable-mexican-sofa | lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb | ComfortableMexicanSofa::ActsAsTree.InstanceMethods.ancestors | def ancestors
node = self
nodes = []
nodes << node = node.parent while node.parent
nodes
end | ruby | def ancestors
node = self
nodes = []
nodes << node = node.parent while node.parent
nodes
end | [
"def",
"ancestors",
"node",
"=",
"self",
"nodes",
"=",
"[",
"]",
"nodes",
"<<",
"node",
"=",
"node",
".",
"parent",
"while",
"node",
".",
"parent",
"nodes",
"end"
] | Returns list of ancestors, starting from parent until root.
subchild1.ancestors # => [child1, root] | [
"Returns",
"list",
"of",
"ancestors",
"starting",
"from",
"parent",
"until",
"root",
"."
] | 38a31428f6e2c07d5bda64f0371eebfb29a3abc4 | https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb#L65-L70 | train |
comfy/comfortable-mexican-sofa | lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb | ComfortableMexicanSofa::ActsAsTree.InstanceMethods.descendants | def descendants
nodes = []
children.each do |c|
nodes << c
nodes << c.descendants
end
nodes.flatten
end | ruby | def descendants
nodes = []
children.each do |c|
nodes << c
nodes << c.descendants
end
nodes.flatten
end | [
"def",
"descendants",
"nodes",
"=",
"[",
"]",
"children",
".",
"each",
"do",
"|",
"c",
"|",
"nodes",
"<<",
"c",
"nodes",
"<<",
"c",
".",
"descendants",
"end",
"nodes",
".",
"flatten",
"end"
] | Returns all children and children of children | [
"Returns",
"all",
"children",
"and",
"children",
"of",
"children"
] | 38a31428f6e2c07d5bda64f0371eebfb29a3abc4 | https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb#L73-L80 | train |
comfy/comfortable-mexican-sofa | lib/comfortable_mexican_sofa/seeds.rb | ComfortableMexicanSofa::Seeds.Exporter.export! | def export!(classes = nil)
classes ||= SEED_CLASSES
classes.each do |klass|
klass = "ComfortableMexicanSofa::Seeds::#{klass}::Exporter"
klass.constantize.new(from, to).export!
end
end | ruby | def export!(classes = nil)
classes ||= SEED_CLASSES
classes.each do |klass|
klass = "ComfortableMexicanSofa::Seeds::#{klass}::Exporter"
klass.constantize.new(from, to).export!
end
end | [
"def",
"export!",
"(",
"classes",
"=",
"nil",
")",
"classes",
"||=",
"SEED_CLASSES",
"classes",
".",
"each",
"do",
"|",
"klass",
"|",
"klass",
"=",
"\"ComfortableMexicanSofa::Seeds::#{klass}::Exporter\"",
"klass",
".",
"constantize",
".",
"new",
"(",
"from",
",",
"to",
")",
".",
"export!",
"end",
"end"
] | if passed nil will use default seed classes | [
"if",
"passed",
"nil",
"will",
"use",
"default",
"seed",
"classes"
] | 38a31428f6e2c07d5bda64f0371eebfb29a3abc4 | https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/seeds.rb#L86-L92 | train |
comfy/comfortable-mexican-sofa | lib/comfortable_mexican_sofa/seeds.rb | ComfortableMexicanSofa::Seeds.Exporter.write_file_content | def write_file_content(path, data)
::File.open(::File.join(path), "wb") do |f|
data.each do |item|
f.write("[#{item[:header]}]\n")
f.write("#{item[:content]}\n")
end
end
end | ruby | def write_file_content(path, data)
::File.open(::File.join(path), "wb") do |f|
data.each do |item|
f.write("[#{item[:header]}]\n")
f.write("#{item[:content]}\n")
end
end
end | [
"def",
"write_file_content",
"(",
"path",
",",
"data",
")",
"::",
"File",
".",
"open",
"(",
"::",
"File",
".",
"join",
"(",
"path",
")",
",",
"\"wb\"",
")",
"do",
"|",
"f",
"|",
"data",
".",
"each",
"do",
"|",
"item",
"|",
"f",
".",
"write",
"(",
"\"[#{item[:header]}]\\n\"",
")",
"f",
".",
"write",
"(",
"\"#{item[:content]}\\n\"",
")",
"end",
"end",
"end"
] | Writing to the seed file. Takes in file handler and array of hashes with
`header` and `content` keys | [
"Writing",
"to",
"the",
"seed",
"file",
".",
"Takes",
"in",
"file",
"handler",
"and",
"array",
"of",
"hashes",
"with",
"header",
"and",
"content",
"keys"
] | 38a31428f6e2c07d5bda64f0371eebfb29a3abc4 | https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/seeds.rb#L98-L105 | train |
comfy/comfortable-mexican-sofa | lib/comfortable_mexican_sofa/seeds/page/exporter.rb | ComfortableMexicanSofa::Seeds::Page.Exporter.fragments_data | def fragments_data(record, page_path)
record.fragments.collect do |frag|
header = "#{frag.tag} #{frag.identifier}"
content =
case frag.tag
when "datetime", "date"
frag.datetime
when "checkbox"
frag.boolean
when "file", "files"
frag.attachments.map do |attachment|
::File.open(::File.join(page_path, attachment.filename.to_s), "wb") do |f|
f.write(attachment.download)
end
attachment.filename
end.join("\n")
else
frag.content
end
{ header: header, content: content }
end
end | ruby | def fragments_data(record, page_path)
record.fragments.collect do |frag|
header = "#{frag.tag} #{frag.identifier}"
content =
case frag.tag
when "datetime", "date"
frag.datetime
when "checkbox"
frag.boolean
when "file", "files"
frag.attachments.map do |attachment|
::File.open(::File.join(page_path, attachment.filename.to_s), "wb") do |f|
f.write(attachment.download)
end
attachment.filename
end.join("\n")
else
frag.content
end
{ header: header, content: content }
end
end | [
"def",
"fragments_data",
"(",
"record",
",",
"page_path",
")",
"record",
".",
"fragments",
".",
"collect",
"do",
"|",
"frag",
"|",
"header",
"=",
"\"#{frag.tag} #{frag.identifier}\"",
"content",
"=",
"case",
"frag",
".",
"tag",
"when",
"\"datetime\"",
",",
"\"date\"",
"frag",
".",
"datetime",
"when",
"\"checkbox\"",
"frag",
".",
"boolean",
"when",
"\"file\"",
",",
"\"files\"",
"frag",
".",
"attachments",
".",
"map",
"do",
"|",
"attachment",
"|",
"::",
"File",
".",
"open",
"(",
"::",
"File",
".",
"join",
"(",
"page_path",
",",
"attachment",
".",
"filename",
".",
"to_s",
")",
",",
"\"wb\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"attachment",
".",
"download",
")",
"end",
"attachment",
".",
"filename",
"end",
".",
"join",
"(",
"\"\\n\"",
")",
"else",
"frag",
".",
"content",
"end",
"{",
"header",
":",
"header",
",",
"content",
":",
"content",
"}",
"end",
"end"
] | Collecting fragment data and writing attachment files to disk | [
"Collecting",
"fragment",
"data",
"and",
"writing",
"attachment",
"files",
"to",
"disk"
] | 38a31428f6e2c07d5bda64f0371eebfb29a3abc4 | https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/seeds/page/exporter.rb#L67-L89 | train |
comfy/comfortable-mexican-sofa | lib/comfortable_mexican_sofa/seeds/page/importer.rb | ComfortableMexicanSofa::Seeds::Page.Importer.import_translations | def import_translations(path, page)
old_translations = page.translations.pluck(:locale)
new_translations = []
Dir["#{path}content.*.html"].each do |file_path|
locale = File.basename(file_path).match(%r{content\.(\w+)\.html})[1]
new_translations << locale
translation = page.translations.where(locale: locale).first_or_initialize
next unless fresh_seed?(translation, file_path)
# reading file content in, resulting in a hash
fragments_hash = parse_file_content(file_path)
# parsing attributes section
attributes_yaml = fragments_hash.delete("attributes")
attrs = YAML.safe_load(attributes_yaml)
# applying attributes
layout = site.layouts.find_by(identifier: attrs.delete("layout")) || page.try(:layout)
translation.attributes = attrs.merge(
layout: layout
)
# applying fragments
old_frag_identifiers = translation.fragments.pluck(:identifier)
new_frag_identifiers, fragments_attributes =
construct_fragments_attributes(fragments_hash, translation, path)
translation.fragments_attributes = fragments_attributes
if translation.save
message = "[CMS SEEDS] Imported Translation \t #{locale}"
ComfortableMexicanSofa.logger.info(message)
# cleaning up old fragments
frags_to_remove = old_frag_identifiers - new_frag_identifiers
translation.fragments.where(identifier: frags_to_remove).destroy_all
else
message = "[CMS SEEDS] Failed to import Translation \n#{locale}"
ComfortableMexicanSofa.logger.warn(message)
end
end
# Cleaning up removed translations
translations_to_remove = old_translations - new_translations
page.translations.where(locale: translations_to_remove).destroy_all
end | ruby | def import_translations(path, page)
old_translations = page.translations.pluck(:locale)
new_translations = []
Dir["#{path}content.*.html"].each do |file_path|
locale = File.basename(file_path).match(%r{content\.(\w+)\.html})[1]
new_translations << locale
translation = page.translations.where(locale: locale).first_or_initialize
next unless fresh_seed?(translation, file_path)
# reading file content in, resulting in a hash
fragments_hash = parse_file_content(file_path)
# parsing attributes section
attributes_yaml = fragments_hash.delete("attributes")
attrs = YAML.safe_load(attributes_yaml)
# applying attributes
layout = site.layouts.find_by(identifier: attrs.delete("layout")) || page.try(:layout)
translation.attributes = attrs.merge(
layout: layout
)
# applying fragments
old_frag_identifiers = translation.fragments.pluck(:identifier)
new_frag_identifiers, fragments_attributes =
construct_fragments_attributes(fragments_hash, translation, path)
translation.fragments_attributes = fragments_attributes
if translation.save
message = "[CMS SEEDS] Imported Translation \t #{locale}"
ComfortableMexicanSofa.logger.info(message)
# cleaning up old fragments
frags_to_remove = old_frag_identifiers - new_frag_identifiers
translation.fragments.where(identifier: frags_to_remove).destroy_all
else
message = "[CMS SEEDS] Failed to import Translation \n#{locale}"
ComfortableMexicanSofa.logger.warn(message)
end
end
# Cleaning up removed translations
translations_to_remove = old_translations - new_translations
page.translations.where(locale: translations_to_remove).destroy_all
end | [
"def",
"import_translations",
"(",
"path",
",",
"page",
")",
"old_translations",
"=",
"page",
".",
"translations",
".",
"pluck",
"(",
":locale",
")",
"new_translations",
"=",
"[",
"]",
"Dir",
"[",
"\"#{path}content.*.html\"",
"]",
".",
"each",
"do",
"|",
"file_path",
"|",
"locale",
"=",
"File",
".",
"basename",
"(",
"file_path",
")",
".",
"match",
"(",
"%r{",
"\\.",
"\\w",
"\\.",
"}",
")",
"[",
"1",
"]",
"new_translations",
"<<",
"locale",
"translation",
"=",
"page",
".",
"translations",
".",
"where",
"(",
"locale",
":",
"locale",
")",
".",
"first_or_initialize",
"next",
"unless",
"fresh_seed?",
"(",
"translation",
",",
"file_path",
")",
"# reading file content in, resulting in a hash",
"fragments_hash",
"=",
"parse_file_content",
"(",
"file_path",
")",
"# parsing attributes section",
"attributes_yaml",
"=",
"fragments_hash",
".",
"delete",
"(",
"\"attributes\"",
")",
"attrs",
"=",
"YAML",
".",
"safe_load",
"(",
"attributes_yaml",
")",
"# applying attributes",
"layout",
"=",
"site",
".",
"layouts",
".",
"find_by",
"(",
"identifier",
":",
"attrs",
".",
"delete",
"(",
"\"layout\"",
")",
")",
"||",
"page",
".",
"try",
"(",
":layout",
")",
"translation",
".",
"attributes",
"=",
"attrs",
".",
"merge",
"(",
"layout",
":",
"layout",
")",
"# applying fragments",
"old_frag_identifiers",
"=",
"translation",
".",
"fragments",
".",
"pluck",
"(",
":identifier",
")",
"new_frag_identifiers",
",",
"fragments_attributes",
"=",
"construct_fragments_attributes",
"(",
"fragments_hash",
",",
"translation",
",",
"path",
")",
"translation",
".",
"fragments_attributes",
"=",
"fragments_attributes",
"if",
"translation",
".",
"save",
"message",
"=",
"\"[CMS SEEDS] Imported Translation \\t #{locale}\"",
"ComfortableMexicanSofa",
".",
"logger",
".",
"info",
"(",
"message",
")",
"# cleaning up old fragments",
"frags_to_remove",
"=",
"old_frag_identifiers",
"-",
"new_frag_identifiers",
"translation",
".",
"fragments",
".",
"where",
"(",
"identifier",
":",
"frags_to_remove",
")",
".",
"destroy_all",
"else",
"message",
"=",
"\"[CMS SEEDS] Failed to import Translation \\n#{locale}\"",
"ComfortableMexicanSofa",
".",
"logger",
".",
"warn",
"(",
"message",
")",
"end",
"end",
"# Cleaning up removed translations",
"translations_to_remove",
"=",
"old_translations",
"-",
"new_translations",
"page",
".",
"translations",
".",
"where",
"(",
"locale",
":",
"translations_to_remove",
")",
".",
"destroy_all",
"end"
] | Importing translations for given page. They look like `content.locale.html` | [
"Importing",
"translations",
"for",
"given",
"page",
".",
"They",
"look",
"like",
"content",
".",
"locale",
".",
"html"
] | 38a31428f6e2c07d5bda64f0371eebfb29a3abc4 | https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/seeds/page/importer.rb#L101-L150 | train |
comfy/comfortable-mexican-sofa | lib/comfortable_mexican_sofa/seeds/page/importer.rb | ComfortableMexicanSofa::Seeds::Page.Importer.construct_fragments_attributes | def construct_fragments_attributes(hash, record, path)
frag_identifiers = []
frag_attributes = hash.collect do |frag_header, frag_content|
tag, identifier = frag_header.split
frag_hash = {
identifier: identifier,
tag: tag
}
# tracking fragments that need removing later
frag_identifiers << identifier
# based on tag we need to cram content in proper place and proper format
case tag
when "date", "datetime"
frag_hash[:datetime] = frag_content
when "checkbox"
frag_hash[:boolean] = frag_content
when "file", "files"
files, file_ids_destroy = files_content(record, identifier, path, frag_content)
frag_hash[:files] = files
frag_hash[:file_ids_destroy] = file_ids_destroy
else
frag_hash[:content] = frag_content
end
frag_hash
end
[frag_identifiers, frag_attributes]
end | ruby | def construct_fragments_attributes(hash, record, path)
frag_identifiers = []
frag_attributes = hash.collect do |frag_header, frag_content|
tag, identifier = frag_header.split
frag_hash = {
identifier: identifier,
tag: tag
}
# tracking fragments that need removing later
frag_identifiers << identifier
# based on tag we need to cram content in proper place and proper format
case tag
when "date", "datetime"
frag_hash[:datetime] = frag_content
when "checkbox"
frag_hash[:boolean] = frag_content
when "file", "files"
files, file_ids_destroy = files_content(record, identifier, path, frag_content)
frag_hash[:files] = files
frag_hash[:file_ids_destroy] = file_ids_destroy
else
frag_hash[:content] = frag_content
end
frag_hash
end
[frag_identifiers, frag_attributes]
end | [
"def",
"construct_fragments_attributes",
"(",
"hash",
",",
"record",
",",
"path",
")",
"frag_identifiers",
"=",
"[",
"]",
"frag_attributes",
"=",
"hash",
".",
"collect",
"do",
"|",
"frag_header",
",",
"frag_content",
"|",
"tag",
",",
"identifier",
"=",
"frag_header",
".",
"split",
"frag_hash",
"=",
"{",
"identifier",
":",
"identifier",
",",
"tag",
":",
"tag",
"}",
"# tracking fragments that need removing later",
"frag_identifiers",
"<<",
"identifier",
"# based on tag we need to cram content in proper place and proper format",
"case",
"tag",
"when",
"\"date\"",
",",
"\"datetime\"",
"frag_hash",
"[",
":datetime",
"]",
"=",
"frag_content",
"when",
"\"checkbox\"",
"frag_hash",
"[",
":boolean",
"]",
"=",
"frag_content",
"when",
"\"file\"",
",",
"\"files\"",
"files",
",",
"file_ids_destroy",
"=",
"files_content",
"(",
"record",
",",
"identifier",
",",
"path",
",",
"frag_content",
")",
"frag_hash",
"[",
":files",
"]",
"=",
"files",
"frag_hash",
"[",
":file_ids_destroy",
"]",
"=",
"file_ids_destroy",
"else",
"frag_hash",
"[",
":content",
"]",
"=",
"frag_content",
"end",
"frag_hash",
"end",
"[",
"frag_identifiers",
",",
"frag_attributes",
"]",
"end"
] | Constructing frag attributes hash that can be assigned to page or translation
also returning list of frag identifiers so we can destroy old ones | [
"Constructing",
"frag",
"attributes",
"hash",
"that",
"can",
"be",
"assigned",
"to",
"page",
"or",
"translation",
"also",
"returning",
"list",
"of",
"frag",
"identifiers",
"so",
"we",
"can",
"destroy",
"old",
"ones"
] | 38a31428f6e2c07d5bda64f0371eebfb29a3abc4 | https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/seeds/page/importer.rb#L154-L184 | train |
comfy/comfortable-mexican-sofa | lib/comfortable_mexican_sofa/seeds/page/importer.rb | ComfortableMexicanSofa::Seeds::Page.Importer.files_content | def files_content(record, identifier, path, frag_content)
# preparing attachments
files = frag_content.split("\n").collect do |filename|
file_handler = File.open(File.join(path, filename))
{
io: file_handler,
filename: filename,
content_type: MimeMagic.by_magic(file_handler)
}
end
# ensuring that old attachments get removed
ids_destroy = []
if (frag = record.fragments.find_by(identifier: identifier))
ids_destroy = frag.attachments.pluck(:id)
end
[files, ids_destroy]
end | ruby | def files_content(record, identifier, path, frag_content)
# preparing attachments
files = frag_content.split("\n").collect do |filename|
file_handler = File.open(File.join(path, filename))
{
io: file_handler,
filename: filename,
content_type: MimeMagic.by_magic(file_handler)
}
end
# ensuring that old attachments get removed
ids_destroy = []
if (frag = record.fragments.find_by(identifier: identifier))
ids_destroy = frag.attachments.pluck(:id)
end
[files, ids_destroy]
end | [
"def",
"files_content",
"(",
"record",
",",
"identifier",
",",
"path",
",",
"frag_content",
")",
"# preparing attachments",
"files",
"=",
"frag_content",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"collect",
"do",
"|",
"filename",
"|",
"file_handler",
"=",
"File",
".",
"open",
"(",
"File",
".",
"join",
"(",
"path",
",",
"filename",
")",
")",
"{",
"io",
":",
"file_handler",
",",
"filename",
":",
"filename",
",",
"content_type",
":",
"MimeMagic",
".",
"by_magic",
"(",
"file_handler",
")",
"}",
"end",
"# ensuring that old attachments get removed",
"ids_destroy",
"=",
"[",
"]",
"if",
"(",
"frag",
"=",
"record",
".",
"fragments",
".",
"find_by",
"(",
"identifier",
":",
"identifier",
")",
")",
"ids_destroy",
"=",
"frag",
".",
"attachments",
".",
"pluck",
"(",
":id",
")",
"end",
"[",
"files",
",",
"ids_destroy",
"]",
"end"
] | Preparing fragment attachments. Returns hashes with file data for
ActiveStorage and a list of ids of old attachements to destroy | [
"Preparing",
"fragment",
"attachments",
".",
"Returns",
"hashes",
"with",
"file",
"data",
"for",
"ActiveStorage",
"and",
"a",
"list",
"of",
"ids",
"of",
"old",
"attachements",
"to",
"destroy"
] | 38a31428f6e2c07d5bda64f0371eebfb29a3abc4 | https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/seeds/page/importer.rb#L188-L206 | train |
comfy/comfortable-mexican-sofa | app/helpers/comfy/cms_helper.rb | Comfy.CmsHelper.cms_fragment_render | def cms_fragment_render(identifier, page = @cms_page)
node = page.fragment_nodes.detect { |n| n.identifier == identifier.to_s }
return "" unless node
node.renderable = true
render inline: page.render([node])
end | ruby | def cms_fragment_render(identifier, page = @cms_page)
node = page.fragment_nodes.detect { |n| n.identifier == identifier.to_s }
return "" unless node
node.renderable = true
render inline: page.render([node])
end | [
"def",
"cms_fragment_render",
"(",
"identifier",
",",
"page",
"=",
"@cms_page",
")",
"node",
"=",
"page",
".",
"fragment_nodes",
".",
"detect",
"{",
"|",
"n",
"|",
"n",
".",
"identifier",
"==",
"identifier",
".",
"to_s",
"}",
"return",
"\"\"",
"unless",
"node",
"node",
".",
"renderable",
"=",
"true",
"render",
"inline",
":",
"page",
".",
"render",
"(",
"[",
"node",
"]",
")",
"end"
] | Same as cms_fragment_content but with cms tags expanded and rendered. Use
it only if you know you got more stuff in the fragment content other than
text because this is a potentially expensive call. | [
"Same",
"as",
"cms_fragment_content",
"but",
"with",
"cms",
"tags",
"expanded",
"and",
"rendered",
".",
"Use",
"it",
"only",
"if",
"you",
"know",
"you",
"got",
"more",
"stuff",
"in",
"the",
"fragment",
"content",
"other",
"than",
"text",
"because",
"this",
"is",
"a",
"potentially",
"expensive",
"call",
"."
] | 38a31428f6e2c07d5bda64f0371eebfb29a3abc4 | https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/app/helpers/comfy/cms_helper.rb#L29-L34 | train |
comfy/comfortable-mexican-sofa | app/helpers/comfy/cms_helper.rb | Comfy.CmsHelper.cms_snippet_render | def cms_snippet_render(identifier, cms_site = @cms_site)
cms_site ||= cms_site_detect
snippet = cms_site&.snippets&.find_by_identifier(identifier)
return "" unless snippet
r = ComfortableMexicanSofa::Content::Renderer.new(snippet)
render inline: r.render(r.nodes(r.tokenize(snippet.content)))
end | ruby | def cms_snippet_render(identifier, cms_site = @cms_site)
cms_site ||= cms_site_detect
snippet = cms_site&.snippets&.find_by_identifier(identifier)
return "" unless snippet
r = ComfortableMexicanSofa::Content::Renderer.new(snippet)
render inline: r.render(r.nodes(r.tokenize(snippet.content)))
end | [
"def",
"cms_snippet_render",
"(",
"identifier",
",",
"cms_site",
"=",
"@cms_site",
")",
"cms_site",
"||=",
"cms_site_detect",
"snippet",
"=",
"cms_site",
"&.",
"snippets",
"&.",
"find_by_identifier",
"(",
"identifier",
")",
"return",
"\"\"",
"unless",
"snippet",
"r",
"=",
"ComfortableMexicanSofa",
"::",
"Content",
"::",
"Renderer",
".",
"new",
"(",
"snippet",
")",
"render",
"inline",
":",
"r",
".",
"render",
"(",
"r",
".",
"nodes",
"(",
"r",
".",
"tokenize",
"(",
"snippet",
".",
"content",
")",
")",
")",
"end"
] | Same as cms_snippet_content but cms tags will be expanded. Note that there
is no page context, so snippet cannot contain fragment tags. | [
"Same",
"as",
"cms_snippet_content",
"but",
"cms",
"tags",
"will",
"be",
"expanded",
".",
"Note",
"that",
"there",
"is",
"no",
"page",
"context",
"so",
"snippet",
"cannot",
"contain",
"fragment",
"tags",
"."
] | 38a31428f6e2c07d5bda64f0371eebfb29a3abc4 | https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/app/helpers/comfy/cms_helper.rb#L48-L54 | train |
comfy/comfortable-mexican-sofa | app/helpers/comfy/cms_helper.rb | Comfy.CmsHelper.comfy_paginate | def comfy_paginate(collection)
return unless collection
if defined?(WillPaginate)
will_paginate collection
elsif defined?(Kaminari)
paginate collection, theme: "comfy"
end
end | ruby | def comfy_paginate(collection)
return unless collection
if defined?(WillPaginate)
will_paginate collection
elsif defined?(Kaminari)
paginate collection, theme: "comfy"
end
end | [
"def",
"comfy_paginate",
"(",
"collection",
")",
"return",
"unless",
"collection",
"if",
"defined?",
"(",
"WillPaginate",
")",
"will_paginate",
"collection",
"elsif",
"defined?",
"(",
"Kaminari",
")",
"paginate",
"collection",
",",
"theme",
":",
"\"comfy\"",
"end",
"end"
] | Wrapper to deal with Kaminari vs WillPaginate | [
"Wrapper",
"to",
"deal",
"with",
"Kaminari",
"vs",
"WillPaginate"
] | 38a31428f6e2c07d5bda64f0371eebfb29a3abc4 | https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/app/helpers/comfy/cms_helper.rb#L63-L70 | train |
sumoheavy/jira-ruby | lib/jira/client.rb | JIRA.Client.post | def post(path, body = '', headers = {})
headers = { 'Content-Type' => 'application/json' }.merge(headers)
request(:post, path, body, merge_default_headers(headers))
end | ruby | def post(path, body = '', headers = {})
headers = { 'Content-Type' => 'application/json' }.merge(headers)
request(:post, path, body, merge_default_headers(headers))
end | [
"def",
"post",
"(",
"path",
",",
"body",
"=",
"''",
",",
"headers",
"=",
"{",
"}",
")",
"headers",
"=",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
".",
"merge",
"(",
"headers",
")",
"request",
"(",
":post",
",",
"path",
",",
"body",
",",
"merge_default_headers",
"(",
"headers",
")",
")",
"end"
] | HTTP methods with a body | [
"HTTP",
"methods",
"with",
"a",
"body"
] | 25e896f227ab81c528e9678708cb546d2f62f018 | https://github.com/sumoheavy/jira-ruby/blob/25e896f227ab81c528e9678708cb546d2f62f018/lib/jira/client.rb#L228-L231 | train |
sumoheavy/jira-ruby | lib/jira/base.rb | JIRA.Base.respond_to? | def respond_to?(method_name, _include_all = false)
if attrs.key?(method_name.to_s)
true
else
super(method_name)
end
end | ruby | def respond_to?(method_name, _include_all = false)
if attrs.key?(method_name.to_s)
true
else
super(method_name)
end
end | [
"def",
"respond_to?",
"(",
"method_name",
",",
"_include_all",
"=",
"false",
")",
"if",
"attrs",
".",
"key?",
"(",
"method_name",
".",
"to_s",
")",
"true",
"else",
"super",
"(",
"method_name",
")",
"end",
"end"
] | Checks if method_name is set in the attributes hash
and returns true when found, otherwise proxies the
call to the superclass. | [
"Checks",
"if",
"method_name",
"is",
"set",
"in",
"the",
"attributes",
"hash",
"and",
"returns",
"true",
"when",
"found",
"otherwise",
"proxies",
"the",
"call",
"to",
"the",
"superclass",
"."
] | 25e896f227ab81c528e9678708cb546d2f62f018 | https://github.com/sumoheavy/jira-ruby/blob/25e896f227ab81c528e9678708cb546d2f62f018/lib/jira/base.rb#L290-L296 | train |
sumoheavy/jira-ruby | lib/jira/base.rb | JIRA.Base.method_missing | def method_missing(method_name, *_args)
if attrs.key?(method_name.to_s)
attrs[method_name.to_s]
else
super(method_name)
end
end | ruby | def method_missing(method_name, *_args)
if attrs.key?(method_name.to_s)
attrs[method_name.to_s]
else
super(method_name)
end
end | [
"def",
"method_missing",
"(",
"method_name",
",",
"*",
"_args",
")",
"if",
"attrs",
".",
"key?",
"(",
"method_name",
".",
"to_s",
")",
"attrs",
"[",
"method_name",
".",
"to_s",
"]",
"else",
"super",
"(",
"method_name",
")",
"end",
"end"
] | Overrides method_missing to check the attribute hash
for resources matching method_name and proxies the call
to the superclass if no match is found. | [
"Overrides",
"method_missing",
"to",
"check",
"the",
"attribute",
"hash",
"for",
"resources",
"matching",
"method_name",
"and",
"proxies",
"the",
"call",
"to",
"the",
"superclass",
"if",
"no",
"match",
"is",
"found",
"."
] | 25e896f227ab81c528e9678708cb546d2f62f018 | https://github.com/sumoheavy/jira-ruby/blob/25e896f227ab81c528e9678708cb546d2f62f018/lib/jira/base.rb#L301-L307 | train |
sumoheavy/jira-ruby | lib/jira/base.rb | JIRA.Base.fetch | def fetch(reload = false, query_params = {})
return if expanded? && !reload
response = client.get(url_with_query_params(url, query_params))
set_attrs_from_response(response)
@expanded = true
end | ruby | def fetch(reload = false, query_params = {})
return if expanded? && !reload
response = client.get(url_with_query_params(url, query_params))
set_attrs_from_response(response)
@expanded = true
end | [
"def",
"fetch",
"(",
"reload",
"=",
"false",
",",
"query_params",
"=",
"{",
"}",
")",
"return",
"if",
"expanded?",
"&&",
"!",
"reload",
"response",
"=",
"client",
".",
"get",
"(",
"url_with_query_params",
"(",
"url",
",",
"query_params",
")",
")",
"set_attrs_from_response",
"(",
"response",
")",
"@expanded",
"=",
"true",
"end"
] | Fetches the attributes for the specified resource from JIRA unless
the resource is already expanded and the optional force reload flag
is not set | [
"Fetches",
"the",
"attributes",
"for",
"the",
"specified",
"resource",
"from",
"JIRA",
"unless",
"the",
"resource",
"is",
"already",
"expanded",
"and",
"the",
"optional",
"force",
"reload",
"flag",
"is",
"not",
"set"
] | 25e896f227ab81c528e9678708cb546d2f62f018 | https://github.com/sumoheavy/jira-ruby/blob/25e896f227ab81c528e9678708cb546d2f62f018/lib/jira/base.rb#L332-L337 | train |
sumoheavy/jira-ruby | lib/jira/base.rb | JIRA.Base.set_attrs_from_response | def set_attrs_from_response(response)
unless response.body.nil? || (response.body.length < 2)
json = self.class.parse_json(response.body)
set_attrs(json)
end
end | ruby | def set_attrs_from_response(response)
unless response.body.nil? || (response.body.length < 2)
json = self.class.parse_json(response.body)
set_attrs(json)
end
end | [
"def",
"set_attrs_from_response",
"(",
"response",
")",
"unless",
"response",
".",
"body",
".",
"nil?",
"||",
"(",
"response",
".",
"body",
".",
"length",
"<",
"2",
")",
"json",
"=",
"self",
".",
"class",
".",
"parse_json",
"(",
"response",
".",
"body",
")",
"set_attrs",
"(",
"json",
")",
"end",
"end"
] | Sets the attributes hash from a HTTPResponse object from JIRA if it is
not nil or is not a json response. | [
"Sets",
"the",
"attributes",
"hash",
"from",
"a",
"HTTPResponse",
"object",
"from",
"JIRA",
"if",
"it",
"is",
"not",
"nil",
"or",
"is",
"not",
"a",
"json",
"response",
"."
] | 25e896f227ab81c528e9678708cb546d2f62f018 | https://github.com/sumoheavy/jira-ruby/blob/25e896f227ab81c528e9678708cb546d2f62f018/lib/jira/base.rb#L380-L385 | train |
Subsets and Splits