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 |
---|---|---|---|---|---|---|---|---|---|---|---|
dagrz/nba_stats | lib/nba_stats/stats/box_score_four_factors.rb | NbaStats.BoxScoreFourFactors.box_score_four_factors | def box_score_four_factors(
game_id,
range_type=0,
start_period=0,
end_period=0,
start_range=0,
end_range=0
)
NbaStats::Resources::BoxScoreFourFactors.new(
get(BOX_SCORE_FOUR_FACTORS_PATH, {
:GameID => game_id,
:RangeType => range_type,
:StartPeriod => start_period,
:EndPeriod => end_period,
:StartRange => start_range,
:EndRange => end_range
})
)
end | ruby | def box_score_four_factors(
game_id,
range_type=0,
start_period=0,
end_period=0,
start_range=0,
end_range=0
)
NbaStats::Resources::BoxScoreFourFactors.new(
get(BOX_SCORE_FOUR_FACTORS_PATH, {
:GameID => game_id,
:RangeType => range_type,
:StartPeriod => start_period,
:EndPeriod => end_period,
:StartRange => start_range,
:EndRange => end_range
})
)
end | [
"def",
"box_score_four_factors",
"(",
"game_id",
",",
"range_type",
"=",
"0",
",",
"start_period",
"=",
"0",
",",
"end_period",
"=",
"0",
",",
"start_range",
"=",
"0",
",",
"end_range",
"=",
"0",
")",
"NbaStats",
"::",
"Resources",
"::",
"BoxScoreFourFactors",
".",
"new",
"(",
"get",
"(",
"BOX_SCORE_FOUR_FACTORS_PATH",
",",
"{",
":GameID",
"=>",
"game_id",
",",
":RangeType",
"=>",
"range_type",
",",
":StartPeriod",
"=>",
"start_period",
",",
":EndPeriod",
"=>",
"end_period",
",",
":StartRange",
"=>",
"start_range",
",",
":EndRange",
"=>",
"end_range",
"}",
")",
")",
"end"
] | Calls the boxscorefourfactors API and returns a BoxScoreFourFactors resource.
@param game_id [String]
@param range_type [Integer]
@param start_period [Integer]
@param end_period [Integer]
@param start_range [Integer]
@param end_range [Integer]
@return [NbaStats::Resources::BoxScoreFourFactors] | [
"Calls",
"the",
"boxscorefourfactors",
"API",
"and",
"returns",
"a",
"BoxScoreFourFactors",
"resource",
"."
] | d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa | https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/box_score_four_factors.rb#L19-L37 | train |
dcuddeback/rspec-tag_matchers | lib/rspec/tag_matchers/has_tag.rb | RSpec::TagMatchers.HasTag.matches? | def matches?(rendered)
@rendered = rendered
matches = Nokogiri::HTML::Document.parse(@rendered.to_s).css(@name).select do |element|
matches_attributes?(element) && matches_content?(element) && matches_criteria?(element)
end
matches_count?(matches)
end | ruby | def matches?(rendered)
@rendered = rendered
matches = Nokogiri::HTML::Document.parse(@rendered.to_s).css(@name).select do |element|
matches_attributes?(element) && matches_content?(element) && matches_criteria?(element)
end
matches_count?(matches)
end | [
"def",
"matches?",
"(",
"rendered",
")",
"@rendered",
"=",
"rendered",
"matches",
"=",
"Nokogiri",
"::",
"HTML",
"::",
"Document",
".",
"parse",
"(",
"@rendered",
".",
"to_s",
")",
".",
"css",
"(",
"@name",
")",
".",
"select",
"do",
"|",
"element",
"|",
"matches_attributes?",
"(",
"element",
")",
"&&",
"matches_content?",
"(",
"element",
")",
"&&",
"matches_criteria?",
"(",
"element",
")",
"end",
"matches_count?",
"(",
"matches",
")",
"end"
] | Answers whether or not the matcher matches any elements within +rendered+.
@param [String] rendered A string of HTML or an Object whose +to_s+ method returns HTML.
(That includes Nokogiri classes.)
@return [Boolean] | [
"Answers",
"whether",
"or",
"not",
"the",
"matcher",
"matches",
"any",
"elements",
"within",
"+",
"rendered",
"+",
"."
] | 6396a833d99ea669699afb1b3dfc62c4512c8882 | https://github.com/dcuddeback/rspec-tag_matchers/blob/6396a833d99ea669699afb1b3dfc62c4512c8882/lib/rspec/tag_matchers/has_tag.rb#L140-L146 | train |
dcuddeback/rspec-tag_matchers | lib/rspec/tag_matchers/has_tag.rb | RSpec::TagMatchers.HasTag.grouped_attributes_description | def grouped_attributes_description(attributes)
make_sentence(
attributes.sort_by{ |key, value| key.to_s }.map do |key, value|
attribute_description(key, value)
end
)
end | ruby | def grouped_attributes_description(attributes)
make_sentence(
attributes.sort_by{ |key, value| key.to_s }.map do |key, value|
attribute_description(key, value)
end
)
end | [
"def",
"grouped_attributes_description",
"(",
"attributes",
")",
"make_sentence",
"(",
"attributes",
".",
"sort_by",
"{",
"|",
"key",
",",
"value",
"|",
"key",
".",
"to_s",
"}",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"attribute_description",
"(",
"key",
",",
"value",
")",
"end",
")",
"end"
] | Describes a group of attribute criteria, combining them into a sentence fragment, with
punctuation and conjunctions if necessary.
@param [Array] attributes A list of <tt>[key, value]</tt> pairs that describe the attribute
criteria.
@return [String] | [
"Describes",
"a",
"group",
"of",
"attribute",
"criteria",
"combining",
"them",
"into",
"a",
"sentence",
"fragment",
"with",
"punctuation",
"and",
"conjunctions",
"if",
"necessary",
"."
] | 6396a833d99ea669699afb1b3dfc62c4512c8882 | https://github.com/dcuddeback/rspec-tag_matchers/blob/6396a833d99ea669699afb1b3dfc62c4512c8882/lib/rspec/tag_matchers/has_tag.rb#L358-L364 | train |
dagrz/nba_stats | lib/nba_stats/stats/player_profile.rb | NbaStats.PlayerProfile.player_profile | def player_profile(
player_id,
season,
graph_start_season,
graph_end_season,
graph_stat=NbaStats::Constants::GRAPH_STAT_POINTS,
season_type=NbaStats::Constants::SEASON_TYPE_REGULAR,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::PlayerProfile.new(
get(PLAYER_PROFILE_PATH, {
:Season => season,
:SeasonType => season_type,
:LeagueID => league_id,
:PlayerID => player_id,
:GraphStartSeason => graph_start_season,
:GraphEndSeason => graph_end_season,
:GraphStat => graph_stat
})
)
end | ruby | def player_profile(
player_id,
season,
graph_start_season,
graph_end_season,
graph_stat=NbaStats::Constants::GRAPH_STAT_POINTS,
season_type=NbaStats::Constants::SEASON_TYPE_REGULAR,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::PlayerProfile.new(
get(PLAYER_PROFILE_PATH, {
:Season => season,
:SeasonType => season_type,
:LeagueID => league_id,
:PlayerID => player_id,
:GraphStartSeason => graph_start_season,
:GraphEndSeason => graph_end_season,
:GraphStat => graph_stat
})
)
end | [
"def",
"player_profile",
"(",
"player_id",
",",
"season",
",",
"graph_start_season",
",",
"graph_end_season",
",",
"graph_stat",
"=",
"NbaStats",
"::",
"Constants",
"::",
"GRAPH_STAT_POINTS",
",",
"season_type",
"=",
"NbaStats",
"::",
"Constants",
"::",
"SEASON_TYPE_REGULAR",
",",
"league_id",
"=",
"NbaStats",
"::",
"Constants",
"::",
"LEAGUE_ID_NBA",
")",
"NbaStats",
"::",
"Resources",
"::",
"PlayerProfile",
".",
"new",
"(",
"get",
"(",
"PLAYER_PROFILE_PATH",
",",
"{",
":Season",
"=>",
"season",
",",
":SeasonType",
"=>",
"season_type",
",",
":LeagueID",
"=>",
"league_id",
",",
":PlayerID",
"=>",
"player_id",
",",
":GraphStartSeason",
"=>",
"graph_start_season",
",",
":GraphEndSeason",
"=>",
"graph_end_season",
",",
":GraphStat",
"=>",
"graph_stat",
"}",
")",
")",
"end"
] | Calls the playerprofile API and returns a PlayerProfile resource.
@param player_id [Integer]
@param season [String]
@param graph_start_season [String]
@param graph_end_season [String]
@param graph_stat [String]
@param season_type [String]
@param league_id [String]
@return [NbaStats::Resources::PlayerProfile] | [
"Calls",
"the",
"playerprofile",
"API",
"and",
"returns",
"a",
"PlayerProfile",
"resource",
"."
] | d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa | https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/player_profile.rb#L21-L41 | train |
dagrz/nba_stats | lib/nba_stats/stats/player_career_stats.rb | NbaStats.PlayerCareerStats.player_career_stats | def player_career_stats(
player_id,
per_mode=NbaStats::Constants::PER_MODE_TOTALS,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::PlayerCareerStats.new(
get(PLAYER_CAREER_STATS_PATH, {
:PlayerID => player_id,
:LeagueID => league_id,
:PerMode => per_mode
})
)
end | ruby | def player_career_stats(
player_id,
per_mode=NbaStats::Constants::PER_MODE_TOTALS,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::PlayerCareerStats.new(
get(PLAYER_CAREER_STATS_PATH, {
:PlayerID => player_id,
:LeagueID => league_id,
:PerMode => per_mode
})
)
end | [
"def",
"player_career_stats",
"(",
"player_id",
",",
"per_mode",
"=",
"NbaStats",
"::",
"Constants",
"::",
"PER_MODE_TOTALS",
",",
"league_id",
"=",
"NbaStats",
"::",
"Constants",
"::",
"LEAGUE_ID_NBA",
")",
"NbaStats",
"::",
"Resources",
"::",
"PlayerCareerStats",
".",
"new",
"(",
"get",
"(",
"PLAYER_CAREER_STATS_PATH",
",",
"{",
":PlayerID",
"=>",
"player_id",
",",
":LeagueID",
"=>",
"league_id",
",",
":PerMode",
"=>",
"per_mode",
"}",
")",
")",
"end"
] | Calls the playercareerstats API and returns a PlayerCareerStats resource.
@param player_id [Integer]
@param per_mode [String]
@param league_id [String]
@return [NbaStats::Resources::PlayerCareerStats] | [
"Calls",
"the",
"playercareerstats",
"API",
"and",
"returns",
"a",
"PlayerCareerStats",
"resource",
"."
] | d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa | https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/player_career_stats.rb#L16-L28 | train |
jasonl/eden | lib/eden/tokenizers/string_tokenizer.rb | Eden.StringTokenizer.tokenize_non_expanded_string | def tokenize_non_expanded_string( start_delimiter )
delimiter_depth = 0
matched_delimiter = is_matched_delimiter?( start_delimiter )
end_delimiter = find_matching_delimiter( start_delimiter )
advance # Pass the opening delimiter
until((cchar == end_delimiter && delimiter_depth == 0) || @i >= @length)
if matched_delimiter
delimiter_depth += 1 if cchar == start_delimiter
delimiter_depth -= 1 if cchar == end_delimiter
end
if cchar == '\\'
advance(2) # Pass the escaped character
else
advance
end
end
advance # Pass the closing quote
if @state == :regex
advance if ['i', 'm'].include?( cchar )
end
@expr_state = :end
capture_token( @state )
end | ruby | def tokenize_non_expanded_string( start_delimiter )
delimiter_depth = 0
matched_delimiter = is_matched_delimiter?( start_delimiter )
end_delimiter = find_matching_delimiter( start_delimiter )
advance # Pass the opening delimiter
until((cchar == end_delimiter && delimiter_depth == 0) || @i >= @length)
if matched_delimiter
delimiter_depth += 1 if cchar == start_delimiter
delimiter_depth -= 1 if cchar == end_delimiter
end
if cchar == '\\'
advance(2) # Pass the escaped character
else
advance
end
end
advance # Pass the closing quote
if @state == :regex
advance if ['i', 'm'].include?( cchar )
end
@expr_state = :end
capture_token( @state )
end | [
"def",
"tokenize_non_expanded_string",
"(",
"start_delimiter",
")",
"delimiter_depth",
"=",
"0",
"matched_delimiter",
"=",
"is_matched_delimiter?",
"(",
"start_delimiter",
")",
"end_delimiter",
"=",
"find_matching_delimiter",
"(",
"start_delimiter",
")",
"advance",
"until",
"(",
"(",
"cchar",
"==",
"end_delimiter",
"&&",
"delimiter_depth",
"==",
"0",
")",
"||",
"@i",
">=",
"@length",
")",
"if",
"matched_delimiter",
"delimiter_depth",
"+=",
"1",
"if",
"cchar",
"==",
"start_delimiter",
"delimiter_depth",
"-=",
"1",
"if",
"cchar",
"==",
"end_delimiter",
"end",
"if",
"cchar",
"==",
"'\\\\'",
"advance",
"(",
"2",
")",
"else",
"advance",
"end",
"end",
"advance",
"if",
"@state",
"==",
":regex",
"advance",
"if",
"[",
"'i'",
",",
"'m'",
"]",
".",
"include?",
"(",
"cchar",
")",
"end",
"@expr_state",
"=",
":end",
"capture_token",
"(",
"@state",
")",
"end"
] | If a block is given, it gets run after the final delimiter is detected. The
primary purpose for this is to allow the capture of regex modifiers | [
"If",
"a",
"block",
"is",
"given",
"it",
"gets",
"run",
"after",
"the",
"final",
"delimiter",
"is",
"detected",
".",
"The",
"primary",
"purpose",
"for",
"this",
"is",
"to",
"allow",
"the",
"capture",
"of",
"regex",
"modifiers"
] | 8a08a4000c63a6b20c07a872cca2dcb0d263baf9 | https://github.com/jasonl/eden/blob/8a08a4000c63a6b20c07a872cca2dcb0d263baf9/lib/eden/tokenizers/string_tokenizer.rb#L9-L37 | train |
jasonl/eden | lib/eden/tokenizers/string_tokenizer.rb | Eden.StringTokenizer.tokenize_heredoc_delimiter | def tokenize_heredoc_delimiter
offset = 2
if cchar == '-'
advance
offset = 3
end
if cchar =~ /[A-Za-z_]/
advance
advance until /[A-Za-z0-9_]/.match( cchar ).nil?
elsif /['"`]/.match(cchar)
advance_through_quoted_delimiter(cchar)
else
return nil
end
@heredoc_delimiter = thunk[offset..-1]
capture_token( :heredoc_delimiter )
end | ruby | def tokenize_heredoc_delimiter
offset = 2
if cchar == '-'
advance
offset = 3
end
if cchar =~ /[A-Za-z_]/
advance
advance until /[A-Za-z0-9_]/.match( cchar ).nil?
elsif /['"`]/.match(cchar)
advance_through_quoted_delimiter(cchar)
else
return nil
end
@heredoc_delimiter = thunk[offset..-1]
capture_token( :heredoc_delimiter )
end | [
"def",
"tokenize_heredoc_delimiter",
"offset",
"=",
"2",
"if",
"cchar",
"==",
"'-'",
"advance",
"offset",
"=",
"3",
"end",
"if",
"cchar",
"=~",
"/",
"/",
"advance",
"advance",
"until",
"/",
"/",
".",
"match",
"(",
"cchar",
")",
".",
"nil?",
"elsif",
"/",
"/",
".",
"match",
"(",
"cchar",
")",
"advance_through_quoted_delimiter",
"(",
"cchar",
")",
"else",
"return",
"nil",
"end",
"@heredoc_delimiter",
"=",
"thunk",
"[",
"offset",
"..",
"-",
"1",
"]",
"capture_token",
"(",
":heredoc_delimiter",
")",
"end"
] | Called from tokenize_lt_operators when it identifies that
<< is a heredoc delimiter. Expects that '<<' will already
be included in the current thunk. | [
"Called",
"from",
"tokenize_lt_operators",
"when",
"it",
"identifies",
"that",
"<<",
"is",
"a",
"heredoc",
"delimiter",
".",
"Expects",
"that",
"<<",
"will",
"already",
"be",
"included",
"in",
"the",
"current",
"thunk",
"."
] | 8a08a4000c63a6b20c07a872cca2dcb0d263baf9 | https://github.com/jasonl/eden/blob/8a08a4000c63a6b20c07a872cca2dcb0d263baf9/lib/eden/tokenizers/string_tokenizer.rb#L95-L112 | train |
forcedotcom/salesforce-deskcom-api | lib/desk_api/resource.rb | DeskApi.Resource.to_hash | def to_hash
load
{}.tap do |hash|
@_definition.each do |k, v|
hash[k] = v
end
end
end | ruby | def to_hash
load
{}.tap do |hash|
@_definition.each do |k, v|
hash[k] = v
end
end
end | [
"def",
"to_hash",
"load",
"{",
"}",
".",
"tap",
"do",
"|",
"hash",
"|",
"@_definition",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"hash",
"[",
"k",
"]",
"=",
"v",
"end",
"end",
"end"
] | Returns a hash based on the current definition of the resource
@return [Hash] definition hash | [
"Returns",
"a",
"hash",
"based",
"on",
"the",
"current",
"definition",
"of",
"the",
"resource"
] | af1080459215d4cb769e785656bcee1d56696f95 | https://github.com/forcedotcom/salesforce-deskcom-api/blob/af1080459215d4cb769e785656bcee1d56696f95/lib/desk_api/resource.rb#L117-L125 | train |
forcedotcom/salesforce-deskcom-api | lib/desk_api/resource.rb | DeskApi.Resource.respond_to? | def respond_to?(method)
load
meth = method.to_s
return true if is_embedded?(meth)
return true if is_link?(meth)
return true if meth.end_with?('=') and is_field?(meth[0...-1])
return true if is_field?(meth)
super
end | ruby | def respond_to?(method)
load
meth = method.to_s
return true if is_embedded?(meth)
return true if is_link?(meth)
return true if meth.end_with?('=') and is_field?(meth[0...-1])
return true if is_field?(meth)
super
end | [
"def",
"respond_to?",
"(",
"method",
")",
"load",
"meth",
"=",
"method",
".",
"to_s",
"return",
"true",
"if",
"is_embedded?",
"(",
"meth",
")",
"return",
"true",
"if",
"is_link?",
"(",
"meth",
")",
"return",
"true",
"if",
"meth",
".",
"end_with?",
"(",
"'='",
")",
"and",
"is_field?",
"(",
"meth",
"[",
"0",
"...",
"-",
"1",
"]",
")",
"return",
"true",
"if",
"is_field?",
"(",
"meth",
")",
"super",
"end"
] | Checks if this resource responds to a specific method
@param method [String/Symbol]
@return [Boolean] | [
"Checks",
"if",
"this",
"resource",
"responds",
"to",
"a",
"specific",
"method"
] | af1080459215d4cb769e785656bcee1d56696f95 | https://github.com/forcedotcom/salesforce-deskcom-api/blob/af1080459215d4cb769e785656bcee1d56696f95/lib/desk_api/resource.rb#L138-L148 | train |
forcedotcom/salesforce-deskcom-api | lib/desk_api/resource.rb | DeskApi.Resource.get_embedded_resource | def get_embedded_resource(method)
return @_embedded[method] if @_embedded.key?(method)
@_embedded[method] = @_definition['_embedded'][method]
if @_embedded[method].kind_of?(Array)
@_embedded[method].tap do |ary|
ary.map!{ |definition| new_resource(definition, true) } unless ary.first.kind_of?(self.class)
end
else
@_embedded[method] = new_resource(@_embedded[method], true)
end
end | ruby | def get_embedded_resource(method)
return @_embedded[method] if @_embedded.key?(method)
@_embedded[method] = @_definition['_embedded'][method]
if @_embedded[method].kind_of?(Array)
@_embedded[method].tap do |ary|
ary.map!{ |definition| new_resource(definition, true) } unless ary.first.kind_of?(self.class)
end
else
@_embedded[method] = new_resource(@_embedded[method], true)
end
end | [
"def",
"get_embedded_resource",
"(",
"method",
")",
"return",
"@_embedded",
"[",
"method",
"]",
"if",
"@_embedded",
".",
"key?",
"(",
"method",
")",
"@_embedded",
"[",
"method",
"]",
"=",
"@_definition",
"[",
"'_embedded'",
"]",
"[",
"method",
"]",
"if",
"@_embedded",
"[",
"method",
"]",
".",
"kind_of?",
"(",
"Array",
")",
"@_embedded",
"[",
"method",
"]",
".",
"tap",
"do",
"|",
"ary",
"|",
"ary",
".",
"map!",
"{",
"|",
"definition",
"|",
"new_resource",
"(",
"definition",
",",
"true",
")",
"}",
"unless",
"ary",
".",
"first",
".",
"kind_of?",
"(",
"self",
".",
"class",
")",
"end",
"else",
"@_embedded",
"[",
"method",
"]",
"=",
"new_resource",
"(",
"@_embedded",
"[",
"method",
"]",
",",
"true",
")",
"end",
"end"
] | Returns the embedded resource
@param method [String/Symbol]
@return [DeskApi::Resource] | [
"Returns",
"the",
"embedded",
"resource"
] | af1080459215d4cb769e785656bcee1d56696f95 | https://github.com/forcedotcom/salesforce-deskcom-api/blob/af1080459215d4cb769e785656bcee1d56696f95/lib/desk_api/resource.rb#L233-L244 | train |
forcedotcom/salesforce-deskcom-api | lib/desk_api/resource.rb | DeskApi.Resource.get_linked_resource | def get_linked_resource(method)
return @_links[method] if @_links.key?(method)
@_links[method] = @_definition['_links'][method]
if @_links[method] and not @_links[method].kind_of?(self.class)
@_links[method] = new_resource(self.class.build_self_link(@_links[method]))
end
end | ruby | def get_linked_resource(method)
return @_links[method] if @_links.key?(method)
@_links[method] = @_definition['_links'][method]
if @_links[method] and not @_links[method].kind_of?(self.class)
@_links[method] = new_resource(self.class.build_self_link(@_links[method]))
end
end | [
"def",
"get_linked_resource",
"(",
"method",
")",
"return",
"@_links",
"[",
"method",
"]",
"if",
"@_links",
".",
"key?",
"(",
"method",
")",
"@_links",
"[",
"method",
"]",
"=",
"@_definition",
"[",
"'_links'",
"]",
"[",
"method",
"]",
"if",
"@_links",
"[",
"method",
"]",
"and",
"not",
"@_links",
"[",
"method",
"]",
".",
"kind_of?",
"(",
"self",
".",
"class",
")",
"@_links",
"[",
"method",
"]",
"=",
"new_resource",
"(",
"self",
".",
"class",
".",
"build_self_link",
"(",
"@_links",
"[",
"method",
"]",
")",
")",
"end",
"end"
] | Returns the linked resource
@param method [String/Symbol]
@return [DeskApi::Resource] | [
"Returns",
"the",
"linked",
"resource"
] | af1080459215d4cb769e785656bcee1d56696f95 | https://github.com/forcedotcom/salesforce-deskcom-api/blob/af1080459215d4cb769e785656bcee1d56696f95/lib/desk_api/resource.rb#L250-L257 | train |
forcedotcom/salesforce-deskcom-api | lib/desk_api/resource.rb | DeskApi.Resource.method_missing | def method_missing(method, *args, &block)
load
meth = method.to_s
return get_embedded_resource(meth) if is_embedded?(meth)
return get_linked_resource(meth) if is_link?(meth)
return @_changed[meth[0...-1]] = args.first if meth.end_with?('=') and is_field?(meth[0...-1])
return get_field_value(meth) if is_field?(meth)
super(method, *args, &block)
end | ruby | def method_missing(method, *args, &block)
load
meth = method.to_s
return get_embedded_resource(meth) if is_embedded?(meth)
return get_linked_resource(meth) if is_link?(meth)
return @_changed[meth[0...-1]] = args.first if meth.end_with?('=') and is_field?(meth[0...-1])
return get_field_value(meth) if is_field?(meth)
super(method, *args, &block)
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"load",
"meth",
"=",
"method",
".",
"to_s",
"return",
"get_embedded_resource",
"(",
"meth",
")",
"if",
"is_embedded?",
"(",
"meth",
")",
"return",
"get_linked_resource",
"(",
"meth",
")",
"if",
"is_link?",
"(",
"meth",
")",
"return",
"@_changed",
"[",
"meth",
"[",
"0",
"...",
"-",
"1",
"]",
"]",
"=",
"args",
".",
"first",
"if",
"meth",
".",
"end_with?",
"(",
"'='",
")",
"and",
"is_field?",
"(",
"meth",
"[",
"0",
"...",
"-",
"1",
"]",
")",
"return",
"get_field_value",
"(",
"meth",
")",
"if",
"is_field?",
"(",
"meth",
")",
"super",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"end"
] | Returns the requested embedded resource, linked resource or field value,
also allows to set a new field value
@param method [String/Symbol]
@param args [Mixed]
@param block [Proc]
@return [Mixed] | [
"Returns",
"the",
"requested",
"embedded",
"resource",
"linked",
"resource",
"or",
"field",
"value",
"also",
"allows",
"to",
"set",
"a",
"new",
"field",
"value"
] | af1080459215d4cb769e785656bcee1d56696f95 | https://github.com/forcedotcom/salesforce-deskcom-api/blob/af1080459215d4cb769e785656bcee1d56696f95/lib/desk_api/resource.rb#L275-L286 | train |
dagrz/nba_stats | lib/nba_stats/stats/league_dash_player_stats.rb | NbaStats.LeagueDashPlayerStats.league_dash_player_stats | def league_dash_player_stats(
season,
measure_type=NbaStats::Constants::MEASURE_TYPE_BASE,
per_mode=NbaStats::Constants::PER_MODE_GAME,
plus_minus=NbaStats::Constants::NO,
pace_adjust=NbaStats::Constants::NO,
rank=NbaStats::Constants::NO,
outcome=nil,
location=nil,
month=0,
season_segment=nil,
date_from=nil,
date_to=nil,
opponent_team_id=0,
vs_conference=nil,
vs_division=nil,
game_segment=nil,
period=0,
last_n_games=0,
game_scope=nil,
player_experience=nil,
player_position=nil,
starter_bench=nil,
conf=NbaStats::Constants::CONF_BOTH,
season_type=NbaStats::Constants::SEASON_TYPE_REGULAR,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
unless date_from.nil?
date_from = date_from.strftime('%m-%d-%Y')
end
unless date_to.nil?
date_to = date_to.strftime('%m-%d-%Y')
end
NbaStats::Resources::LeagueDashPlayerStats.new(
get(LEAGUE_DASH_PLAYER_STATS_PATH, {
:Season => season,
:SeasonType => season_type,
:LeagueID => league_id,
:MeasureType => measure_type,
:PerMode => per_mode,
:PlusMinus => plus_minus,
:PaceAdjust => pace_adjust,
:Rank => rank,
:Outcome => outcome,
:Location => location,
:Month => month,
:SeasonSegment => season_segment,
:DateFrom => date_from,
:DateTo => date_to,
:OpponentTeamID => opponent_team_id,
:VsConference => vs_conference,
:VsDivision => vs_division,
:GameSegment => game_segment,
:Period => period,
:LastNGames => last_n_games,
:GameScope => game_scope,
:PlayerExperience => player_experience,
:PlayerPosition => player_position,
:StarterBench => starter_bench,
:Conf => conf
})
)
end | ruby | def league_dash_player_stats(
season,
measure_type=NbaStats::Constants::MEASURE_TYPE_BASE,
per_mode=NbaStats::Constants::PER_MODE_GAME,
plus_minus=NbaStats::Constants::NO,
pace_adjust=NbaStats::Constants::NO,
rank=NbaStats::Constants::NO,
outcome=nil,
location=nil,
month=0,
season_segment=nil,
date_from=nil,
date_to=nil,
opponent_team_id=0,
vs_conference=nil,
vs_division=nil,
game_segment=nil,
period=0,
last_n_games=0,
game_scope=nil,
player_experience=nil,
player_position=nil,
starter_bench=nil,
conf=NbaStats::Constants::CONF_BOTH,
season_type=NbaStats::Constants::SEASON_TYPE_REGULAR,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
unless date_from.nil?
date_from = date_from.strftime('%m-%d-%Y')
end
unless date_to.nil?
date_to = date_to.strftime('%m-%d-%Y')
end
NbaStats::Resources::LeagueDashPlayerStats.new(
get(LEAGUE_DASH_PLAYER_STATS_PATH, {
:Season => season,
:SeasonType => season_type,
:LeagueID => league_id,
:MeasureType => measure_type,
:PerMode => per_mode,
:PlusMinus => plus_minus,
:PaceAdjust => pace_adjust,
:Rank => rank,
:Outcome => outcome,
:Location => location,
:Month => month,
:SeasonSegment => season_segment,
:DateFrom => date_from,
:DateTo => date_to,
:OpponentTeamID => opponent_team_id,
:VsConference => vs_conference,
:VsDivision => vs_division,
:GameSegment => game_segment,
:Period => period,
:LastNGames => last_n_games,
:GameScope => game_scope,
:PlayerExperience => player_experience,
:PlayerPosition => player_position,
:StarterBench => starter_bench,
:Conf => conf
})
)
end | [
"def",
"league_dash_player_stats",
"(",
"season",
",",
"measure_type",
"=",
"NbaStats",
"::",
"Constants",
"::",
"MEASURE_TYPE_BASE",
",",
"per_mode",
"=",
"NbaStats",
"::",
"Constants",
"::",
"PER_MODE_GAME",
",",
"plus_minus",
"=",
"NbaStats",
"::",
"Constants",
"::",
"NO",
",",
"pace_adjust",
"=",
"NbaStats",
"::",
"Constants",
"::",
"NO",
",",
"rank",
"=",
"NbaStats",
"::",
"Constants",
"::",
"NO",
",",
"outcome",
"=",
"nil",
",",
"location",
"=",
"nil",
",",
"month",
"=",
"0",
",",
"season_segment",
"=",
"nil",
",",
"date_from",
"=",
"nil",
",",
"date_to",
"=",
"nil",
",",
"opponent_team_id",
"=",
"0",
",",
"vs_conference",
"=",
"nil",
",",
"vs_division",
"=",
"nil",
",",
"game_segment",
"=",
"nil",
",",
"period",
"=",
"0",
",",
"last_n_games",
"=",
"0",
",",
"game_scope",
"=",
"nil",
",",
"player_experience",
"=",
"nil",
",",
"player_position",
"=",
"nil",
",",
"starter_bench",
"=",
"nil",
",",
"conf",
"=",
"NbaStats",
"::",
"Constants",
"::",
"CONF_BOTH",
",",
"season_type",
"=",
"NbaStats",
"::",
"Constants",
"::",
"SEASON_TYPE_REGULAR",
",",
"league_id",
"=",
"NbaStats",
"::",
"Constants",
"::",
"LEAGUE_ID_NBA",
")",
"unless",
"date_from",
".",
"nil?",
"date_from",
"=",
"date_from",
".",
"strftime",
"(",
"'%m-%d-%Y'",
")",
"end",
"unless",
"date_to",
".",
"nil?",
"date_to",
"=",
"date_to",
".",
"strftime",
"(",
"'%m-%d-%Y'",
")",
"end",
"NbaStats",
"::",
"Resources",
"::",
"LeagueDashPlayerStats",
".",
"new",
"(",
"get",
"(",
"LEAGUE_DASH_PLAYER_STATS_PATH",
",",
"{",
":Season",
"=>",
"season",
",",
":SeasonType",
"=>",
"season_type",
",",
":LeagueID",
"=>",
"league_id",
",",
":MeasureType",
"=>",
"measure_type",
",",
":PerMode",
"=>",
"per_mode",
",",
":PlusMinus",
"=>",
"plus_minus",
",",
":PaceAdjust",
"=>",
"pace_adjust",
",",
":Rank",
"=>",
"rank",
",",
":Outcome",
"=>",
"outcome",
",",
":Location",
"=>",
"location",
",",
":Month",
"=>",
"month",
",",
":SeasonSegment",
"=>",
"season_segment",
",",
":DateFrom",
"=>",
"date_from",
",",
":DateTo",
"=>",
"date_to",
",",
":OpponentTeamID",
"=>",
"opponent_team_id",
",",
":VsConference",
"=>",
"vs_conference",
",",
":VsDivision",
"=>",
"vs_division",
",",
":GameSegment",
"=>",
"game_segment",
",",
":Period",
"=>",
"period",
",",
":LastNGames",
"=>",
"last_n_games",
",",
":GameScope",
"=>",
"game_scope",
",",
":PlayerExperience",
"=>",
"player_experience",
",",
":PlayerPosition",
"=>",
"player_position",
",",
":StarterBench",
"=>",
"starter_bench",
",",
":Conf",
"=>",
"conf",
"}",
")",
")",
"end"
] | Calls the leaguedashplayerstats API and returns a LeagueDashPlayerStats resource.
@param season [String]
@param measure_type [String]
@param per_mode [String]
@param plus_minus [String]
@param pace_adjust [String]
@param rank [String]
@param outcome [String]
@param location [String]
@param month [Integer]
@param season_segment [xxxxxxxxxx]
@param date_from [Date]
@param date_to [Date]
@param opponent_team_id [Integer]
@param vs_conference [String]
@param vs_division [String]
@param game_segment [String]
@param period [Integer]
@param last_n_games [Integer]
@param game_scope [String]
@param player_experience [String]
@param player_position [String]
@param starter_bench [String]
@param conf [String]
@param season_type [String]
@param league_id [String]
@return [NbaStats::Resources::LeagueDashPlayerStats] | [
"Calls",
"the",
"leaguedashplayerstats",
"API",
"and",
"returns",
"a",
"LeagueDashPlayerStats",
"resource",
"."
] | d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa | https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/league_dash_player_stats.rb#L38-L100 | train |
dagrz/nba_stats | lib/nba_stats/stats/box_score.rb | NbaStats.BoxScore.box_score | def box_score(
game_id,
range_type=0,
start_period=0,
end_period=0,
start_range=0,
end_range=0
)
NbaStats::Resources::BoxScore.new(
get(BOX_SCORE_PATH, {
:GameID => game_id,
:RangeType => range_type,
:StartPeriod => start_period,
:EndPeriod => end_period,
:StartRange => start_range,
:EndRange => end_range
})
)
end | ruby | def box_score(
game_id,
range_type=0,
start_period=0,
end_period=0,
start_range=0,
end_range=0
)
NbaStats::Resources::BoxScore.new(
get(BOX_SCORE_PATH, {
:GameID => game_id,
:RangeType => range_type,
:StartPeriod => start_period,
:EndPeriod => end_period,
:StartRange => start_range,
:EndRange => end_range
})
)
end | [
"def",
"box_score",
"(",
"game_id",
",",
"range_type",
"=",
"0",
",",
"start_period",
"=",
"0",
",",
"end_period",
"=",
"0",
",",
"start_range",
"=",
"0",
",",
"end_range",
"=",
"0",
")",
"NbaStats",
"::",
"Resources",
"::",
"BoxScore",
".",
"new",
"(",
"get",
"(",
"BOX_SCORE_PATH",
",",
"{",
":GameID",
"=>",
"game_id",
",",
":RangeType",
"=>",
"range_type",
",",
":StartPeriod",
"=>",
"start_period",
",",
":EndPeriod",
"=>",
"end_period",
",",
":StartRange",
"=>",
"start_range",
",",
":EndRange",
"=>",
"end_range",
"}",
")",
")",
"end"
] | Calls the boxscore API and returns a BoxScore resource.
@param game_id [String]
@param range_type [Integer]
@param start_period [Integer]
@param end_period [Integer]
@param start_range [Integer]
@param end_range [Integer]
@return [NbaStats::Resources::BoxScore] | [
"Calls",
"the",
"boxscore",
"API",
"and",
"returns",
"a",
"BoxScore",
"resource",
"."
] | d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa | https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/box_score.rb#L20-L38 | train |
kolorahl/rarbac | app/helpers/rarbac/user_helper.rb | Rarbac.UserHelper.has_roles? | def has_roles?(*args)
throw Exception.new("Must supply at least one role.") if args.empty?
roles.where(name: args).count == args.count
end | ruby | def has_roles?(*args)
throw Exception.new("Must supply at least one role.") if args.empty?
roles.where(name: args).count == args.count
end | [
"def",
"has_roles?",
"(",
"*",
"args",
")",
"throw",
"Exception",
".",
"new",
"(",
"\"Must supply at least one role.\"",
")",
"if",
"args",
".",
"empty?",
"roles",
".",
"where",
"(",
"name",
":",
"args",
")",
".",
"count",
"==",
"args",
".",
"count",
"end"
] | Determines if the user has all of the given roles linked to it.
@param [String] args an argument list of one or more roles to check for.
@return [true|false] true if the user is linked to all of the given roles. | [
"Determines",
"if",
"the",
"user",
"has",
"all",
"of",
"the",
"given",
"roles",
"linked",
"to",
"it",
"."
] | 9bb2654da1cec74766ae6a6aa5e46821bb478f47 | https://github.com/kolorahl/rarbac/blob/9bb2654da1cec74766ae6a6aa5e46821bb478f47/app/helpers/rarbac/user_helper.rb#L22-L25 | train |
kolorahl/rarbac | app/helpers/rarbac/user_helper.rb | Rarbac.UserHelper.has_permission? | def has_permission?(action)
return true if Action.where(name: action).count == 0
actions.where(name: action).count > 0
end | ruby | def has_permission?(action)
return true if Action.where(name: action).count == 0
actions.where(name: action).count > 0
end | [
"def",
"has_permission?",
"(",
"action",
")",
"return",
"true",
"if",
"Action",
".",
"where",
"(",
"name",
":",
"action",
")",
".",
"count",
"==",
"0",
"actions",
".",
"where",
"(",
"name",
":",
"action",
")",
".",
"count",
">",
"0",
"end"
] | Determines if the user has permission to a given action. If the action
does not exist at all, it is assumed the action is publicly available.
@param [String] action name of the action to check permission for.
@return [true|false] true if the user has at least one role linked to it
with permission to the given action. | [
"Determines",
"if",
"the",
"user",
"has",
"permission",
"to",
"a",
"given",
"action",
".",
"If",
"the",
"action",
"does",
"not",
"exist",
"at",
"all",
"it",
"is",
"assumed",
"the",
"action",
"is",
"publicly",
"available",
"."
] | 9bb2654da1cec74766ae6a6aa5e46821bb478f47 | https://github.com/kolorahl/rarbac/blob/9bb2654da1cec74766ae6a6aa5e46821bb478f47/app/helpers/rarbac/user_helper.rb#L33-L36 | train |
dagrz/nba_stats | lib/nba_stats/stats/scoreboard.rb | NbaStats.Scoreboard.scoreboard | def scoreboard(
game_date=Date.today,
day_offset=0,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::Scoreboard.new(
get(SCOREBOARD_PATH, {
:LeagueID => league_id,
:GameDate => game_date.strftime('%m-%d-%Y'),
:DayOffset => day_offset
})
)
end | ruby | def scoreboard(
game_date=Date.today,
day_offset=0,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::Scoreboard.new(
get(SCOREBOARD_PATH, {
:LeagueID => league_id,
:GameDate => game_date.strftime('%m-%d-%Y'),
:DayOffset => day_offset
})
)
end | [
"def",
"scoreboard",
"(",
"game_date",
"=",
"Date",
".",
"today",
",",
"day_offset",
"=",
"0",
",",
"league_id",
"=",
"NbaStats",
"::",
"Constants",
"::",
"LEAGUE_ID_NBA",
")",
"NbaStats",
"::",
"Resources",
"::",
"Scoreboard",
".",
"new",
"(",
"get",
"(",
"SCOREBOARD_PATH",
",",
"{",
":LeagueID",
"=>",
"league_id",
",",
":GameDate",
"=>",
"game_date",
".",
"strftime",
"(",
"'%m-%d-%Y'",
")",
",",
":DayOffset",
"=>",
"day_offset",
"}",
")",
")",
"end"
] | Calls the scoreboard API and returns a Scoreboard resource.
@param game_date [Date]
@param day_offset [Integer]
@param league_id [String]
@return [NbaStats::Resources::Scoreboard] | [
"Calls",
"the",
"scoreboard",
"API",
"and",
"returns",
"a",
"Scoreboard",
"resource",
"."
] | d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa | https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/scoreboard.rb#L17-L29 | train |
kudelabs/ad_man | app/helpers/ad_man/application_helper.rb | AdMan.ApplicationHelper.get_keyword_from_url | def get_keyword_from_url
if request.env["REQUEST_PATH"]
req_url = request.env["REQUEST_PATH"].split("/")
keyword_names = Keyword.all.map(&:name)
keyword = req_url & keyword_names
end
end | ruby | def get_keyword_from_url
if request.env["REQUEST_PATH"]
req_url = request.env["REQUEST_PATH"].split("/")
keyword_names = Keyword.all.map(&:name)
keyword = req_url & keyword_names
end
end | [
"def",
"get_keyword_from_url",
"if",
"request",
".",
"env",
"[",
"\"REQUEST_PATH\"",
"]",
"req_url",
"=",
"request",
".",
"env",
"[",
"\"REQUEST_PATH\"",
"]",
".",
"split",
"(",
"\"/\"",
")",
"keyword_names",
"=",
"Keyword",
".",
"all",
".",
"map",
"(",
"&",
":name",
")",
"keyword",
"=",
"req_url",
"&",
"keyword_names",
"end",
"end"
] | grab the keyword form request url | [
"grab",
"the",
"keyword",
"form",
"request",
"url"
] | 9b9eaffd2b42ba67e4a61c4f619e5ee73b6cefd4 | https://github.com/kudelabs/ad_man/blob/9b9eaffd2b42ba67e4a61c4f619e5ee73b6cefd4/app/helpers/ad_man/application_helper.rb#L20-L26 | train |
weltschmerz1/entangled | lib/entangled/helpers.rb | Entangled.Helpers.redis | def redis
if defined?($redis) && $redis
Redis.new($redis.client.options)
elsif defined?(REDIS) && REDIS
Redis.new(REDIS.client.options)
else
Redis.new
end
end | ruby | def redis
if defined?($redis) && $redis
Redis.new($redis.client.options)
elsif defined?(REDIS) && REDIS
Redis.new(REDIS.client.options)
else
Redis.new
end
end | [
"def",
"redis",
"if",
"defined?",
"(",
"$redis",
")",
"&&",
"$redis",
"Redis",
".",
"new",
"(",
"$redis",
".",
"client",
".",
"options",
")",
"elsif",
"defined?",
"(",
"REDIS",
")",
"&&",
"REDIS",
"Redis",
".",
"new",
"(",
"REDIS",
".",
"client",
".",
"options",
")",
"else",
"Redis",
".",
"new",
"end",
"end"
] | Get Redis that user might be using or instantiate
a new one | [
"Get",
"Redis",
"that",
"user",
"might",
"be",
"using",
"or",
"instantiate",
"a",
"new",
"one"
] | 2a8596c669785ce9b367379b8b5a63e13b0afc46 | https://github.com/weltschmerz1/entangled/blob/2a8596c669785ce9b367379b8b5a63e13b0afc46/lib/entangled/helpers.rb#L5-L13 | train |
dagrz/nba_stats | lib/nba_stats/stats/draft_combine_drill_results.rb | NbaStats.DraftCombineDrillResults.draft_combine_drill_results | def draft_combine_drill_results(
season_year,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::DraftCombineDrillResults.new(
get(DRAFT_COMBINE_DRILL_RESULTS_PATH, {
:LeagueID => league_id,
:SeasonYear => season_year
})
)
end | ruby | def draft_combine_drill_results(
season_year,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::DraftCombineDrillResults.new(
get(DRAFT_COMBINE_DRILL_RESULTS_PATH, {
:LeagueID => league_id,
:SeasonYear => season_year
})
)
end | [
"def",
"draft_combine_drill_results",
"(",
"season_year",
",",
"league_id",
"=",
"NbaStats",
"::",
"Constants",
"::",
"LEAGUE_ID_NBA",
")",
"NbaStats",
"::",
"Resources",
"::",
"DraftCombineDrillResults",
".",
"new",
"(",
"get",
"(",
"DRAFT_COMBINE_DRILL_RESULTS_PATH",
",",
"{",
":LeagueID",
"=>",
"league_id",
",",
":SeasonYear",
"=>",
"season_year",
"}",
")",
")",
"end"
] | Calls the draftcombinedrillresults API and returns a DraftCombineDrillResults resource.
@param season_year [String]
@param league_id [String]
@return [NbaStats::Resources::DraftCombineDrillResults] | [
"Calls",
"the",
"draftcombinedrillresults",
"API",
"and",
"returns",
"a",
"DraftCombineDrillResults",
"resource",
"."
] | d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa | https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/draft_combine_drill_results.rb#L15-L25 | train |
dagrz/nba_stats | lib/nba_stats/stats/play_by_play.rb | NbaStats.PlayByPlay.play_by_play | def play_by_play(
game_id,
start_period=0,
end_period=0
)
NbaStats::Resources::PlayByPlay.new(
get(PLAY_BY_PLAY_PATH, {
:GameID => game_id,
:StartPeriod => start_period,
:EndPeriod => end_period
})
)
end | ruby | def play_by_play(
game_id,
start_period=0,
end_period=0
)
NbaStats::Resources::PlayByPlay.new(
get(PLAY_BY_PLAY_PATH, {
:GameID => game_id,
:StartPeriod => start_period,
:EndPeriod => end_period
})
)
end | [
"def",
"play_by_play",
"(",
"game_id",
",",
"start_period",
"=",
"0",
",",
"end_period",
"=",
"0",
")",
"NbaStats",
"::",
"Resources",
"::",
"PlayByPlay",
".",
"new",
"(",
"get",
"(",
"PLAY_BY_PLAY_PATH",
",",
"{",
":GameID",
"=>",
"game_id",
",",
":StartPeriod",
"=>",
"start_period",
",",
":EndPeriod",
"=>",
"end_period",
"}",
")",
")",
"end"
] | Calls the playbyplay API and returns a PlayByPlay resource.
@param game_id [String]
@param start_period [Integer]
@param end_period [Integer]
@return [NbaStats::Resources::PlayByPlay] | [
"Calls",
"the",
"playbyplay",
"API",
"and",
"returns",
"a",
"PlayByPlay",
"resource",
"."
] | d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa | https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/play_by_play.rb#L16-L28 | train |
mat813/rb-kqueue | lib/rb-kqueue/watcher.rb | KQueue.Watcher.native | def native(flags)
native = Native::KEvent.new
native[:ident] = @ident
native[:filter] = Native::Flags.to_flag("EVFILT", @filter)
native[:flags] = Native::Flags.to_mask("EV", @flags | flags)
native[:fflags] = Native::Flags.to_mask("NOTE_#{@filter.to_s.upcase}", @fflags)
native[:data] = @data if @data
native
end | ruby | def native(flags)
native = Native::KEvent.new
native[:ident] = @ident
native[:filter] = Native::Flags.to_flag("EVFILT", @filter)
native[:flags] = Native::Flags.to_mask("EV", @flags | flags)
native[:fflags] = Native::Flags.to_mask("NOTE_#{@filter.to_s.upcase}", @fflags)
native[:data] = @data if @data
native
end | [
"def",
"native",
"(",
"flags",
")",
"native",
"=",
"Native",
"::",
"KEvent",
".",
"new",
"native",
"[",
":ident",
"]",
"=",
"@ident",
"native",
"[",
":filter",
"]",
"=",
"Native",
"::",
"Flags",
".",
"to_flag",
"(",
"\"EVFILT\"",
",",
"@filter",
")",
"native",
"[",
":flags",
"]",
"=",
"Native",
"::",
"Flags",
".",
"to_mask",
"(",
"\"EV\"",
",",
"@flags",
"|",
"flags",
")",
"native",
"[",
":fflags",
"]",
"=",
"Native",
"::",
"Flags",
".",
"to_mask",
"(",
"\"NOTE_#{@filter.to_s.upcase}\"",
",",
"@fflags",
")",
"native",
"[",
":data",
"]",
"=",
"@data",
"if",
"@data",
"native",
"end"
] | Returns a C struct corresponding to this watcher.
@param flags [Array<Symbol>] Flags for the C struct's `flags` field,
in addition to the `@flags` var.
@return [Native::KEvent] | [
"Returns",
"a",
"C",
"struct",
"corresponding",
"to",
"this",
"watcher",
"."
] | f11c1a8552812bc0b635ef9751d6dc61d4beaa67 | https://github.com/mat813/rb-kqueue/blob/f11c1a8552812bc0b635ef9751d6dc61d4beaa67/lib/rb-kqueue/watcher.rb#L100-L108 | train |
mat813/rb-kqueue | lib/rb-kqueue/watcher.rb | KQueue.Watcher.kevent! | def kevent!(*flags)
if Native.kevent(@queue.fd, native(flags).pointer, 1, nil, 0, nil) < 0
KQueue.handle_error
end
end | ruby | def kevent!(*flags)
if Native.kevent(@queue.fd, native(flags).pointer, 1, nil, 0, nil) < 0
KQueue.handle_error
end
end | [
"def",
"kevent!",
"(",
"*",
"flags",
")",
"if",
"Native",
".",
"kevent",
"(",
"@queue",
".",
"fd",
",",
"native",
"(",
"flags",
")",
".",
"pointer",
",",
"1",
",",
"nil",
",",
"0",
",",
"nil",
")",
"<",
"0",
"KQueue",
".",
"handle_error",
"end",
"end"
] | Runs the `kevent` C call with this Watcher's kevent struct as input.
This effectively means telling kqueue to perform some action
with this Watcher as an argument.
@param flags [Array<Symbol>] Flags specifying the action to perform
as well as any additional flags.
@return [void]
@raise [SystemCallError] If something goes wrong when performing the C call. | [
"Runs",
"the",
"kevent",
"C",
"call",
"with",
"this",
"Watcher",
"s",
"kevent",
"struct",
"as",
"input",
".",
"This",
"effectively",
"means",
"telling",
"kqueue",
"to",
"perform",
"some",
"action",
"with",
"this",
"Watcher",
"as",
"an",
"argument",
"."
] | f11c1a8552812bc0b635ef9751d6dc61d4beaa67 | https://github.com/mat813/rb-kqueue/blob/f11c1a8552812bc0b635ef9751d6dc61d4beaa67/lib/rb-kqueue/watcher.rb#L118-L122 | train |
dagrz/nba_stats | lib/nba_stats/stats/draft_combine_non_stationary_shooting.rb | NbaStats.DraftCombineNonStationaryShooting.draft_combine_non_stationary_shooting | def draft_combine_non_stationary_shooting(
season_year,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::DraftCombineNonStationaryShooting.new(
get(DRAFT_COMBINE_NON_STATIONARY_SHOOTING_PATH, {
:LeagueID => league_id,
:SeasonYear => season_year
})
)
end | ruby | def draft_combine_non_stationary_shooting(
season_year,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::DraftCombineNonStationaryShooting.new(
get(DRAFT_COMBINE_NON_STATIONARY_SHOOTING_PATH, {
:LeagueID => league_id,
:SeasonYear => season_year
})
)
end | [
"def",
"draft_combine_non_stationary_shooting",
"(",
"season_year",
",",
"league_id",
"=",
"NbaStats",
"::",
"Constants",
"::",
"LEAGUE_ID_NBA",
")",
"NbaStats",
"::",
"Resources",
"::",
"DraftCombineNonStationaryShooting",
".",
"new",
"(",
"get",
"(",
"DRAFT_COMBINE_NON_STATIONARY_SHOOTING_PATH",
",",
"{",
":LeagueID",
"=>",
"league_id",
",",
":SeasonYear",
"=>",
"season_year",
"}",
")",
")",
"end"
] | Calls the draftcombinenonstationaryshooting API and returns a DraftCombineNonStationaryShooting resource.
@param season_year [String]
@param league_id [String]
@return [NbaStats::Resources::DraftCombineNonStationaryShooting] | [
"Calls",
"the",
"draftcombinenonstationaryshooting",
"API",
"and",
"returns",
"a",
"DraftCombineNonStationaryShooting",
"resource",
"."
] | d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa | https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/draft_combine_non_stationary_shooting.rb#L15-L25 | train |
listia/walmart_open | lib/walmart_open/request.rb | WalmartOpen.Request.convert_param_keys | def convert_param_keys(underscored_params)
pairs = underscored_params.map do |key, value|
key = key.to_s.gsub(/_([a-z])/i) { $1.upcase }
[key, value]
end
Hash[pairs]
end | ruby | def convert_param_keys(underscored_params)
pairs = underscored_params.map do |key, value|
key = key.to_s.gsub(/_([a-z])/i) { $1.upcase }
[key, value]
end
Hash[pairs]
end | [
"def",
"convert_param_keys",
"(",
"underscored_params",
")",
"pairs",
"=",
"underscored_params",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"key",
"=",
"key",
".",
"to_s",
".",
"gsub",
"(",
"/",
"/i",
")",
"{",
"$1",
".",
"upcase",
"}",
"[",
"key",
",",
"value",
"]",
"end",
"Hash",
"[",
"pairs",
"]",
"end"
] | Converts foo_bar_param to fooBarParam. | [
"Converts",
"foo_bar_param",
"to",
"fooBarParam",
"."
] | f563da4ae7b620d7c3c52ebafb6af50a77d614b2 | https://github.com/listia/walmart_open/blob/f563da4ae7b620d7c3c52ebafb6af50a77d614b2/lib/walmart_open/request.rb#L71-L77 | train |
dagrz/nba_stats | lib/nba_stats/stats/box_score_misc.rb | NbaStats.BoxScoreMisc.box_score_misc | def box_score_misc(
game_id,
range_type=0,
start_period=0,
end_period=0,
start_range=0,
end_range=0
)
NbaStats::Resources::BoxScoreMisc.new(
get(BOX_SCORE_MISC_PATH, {
:GameID => game_id,
:RangeType => range_type,
:StartPeriod => start_period,
:EndPeriod => end_period,
:StartRange => start_range,
:EndRange => end_range
})
)
end | ruby | def box_score_misc(
game_id,
range_type=0,
start_period=0,
end_period=0,
start_range=0,
end_range=0
)
NbaStats::Resources::BoxScoreMisc.new(
get(BOX_SCORE_MISC_PATH, {
:GameID => game_id,
:RangeType => range_type,
:StartPeriod => start_period,
:EndPeriod => end_period,
:StartRange => start_range,
:EndRange => end_range
})
)
end | [
"def",
"box_score_misc",
"(",
"game_id",
",",
"range_type",
"=",
"0",
",",
"start_period",
"=",
"0",
",",
"end_period",
"=",
"0",
",",
"start_range",
"=",
"0",
",",
"end_range",
"=",
"0",
")",
"NbaStats",
"::",
"Resources",
"::",
"BoxScoreMisc",
".",
"new",
"(",
"get",
"(",
"BOX_SCORE_MISC_PATH",
",",
"{",
":GameID",
"=>",
"game_id",
",",
":RangeType",
"=>",
"range_type",
",",
":StartPeriod",
"=>",
"start_period",
",",
":EndPeriod",
"=>",
"end_period",
",",
":StartRange",
"=>",
"start_range",
",",
":EndRange",
"=>",
"end_range",
"}",
")",
")",
"end"
] | Calls the boxscoremisc API and returns a BoxScoreMisc resource.
@param game_id [String]
@param range_type [Integer]
@param start_period [Integer]
@param end_period [Integer]
@param start_range [Integer]
@param end_range [Integer]
@return [NbaStats::Resources::BoxScoreMisc] | [
"Calls",
"the",
"boxscoremisc",
"API",
"and",
"returns",
"a",
"BoxScoreMisc",
"resource",
"."
] | d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa | https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/box_score_misc.rb#L19-L37 | train |
dagrz/nba_stats | lib/nba_stats/stats/league_dash_team_stats.rb | NbaStats.LeagueDashTeamStats.league_dash_team_stats | def league_dash_team_stats(
season,
date_from=nil,
date_to=nil,
game_scope=nil,
game_segment=nil,
last_n_games=0,
location=nil,
measure_type=NbaStats::Constants::MEASURE_TYPE_BASE,
month=0,
opponent_team_id=0,
outcome=nil,
pace_adjust=NbaStats::Constants::NO,
per_mode=NbaStats::Constants::PER_MODE_GAME,
period=0,
player_experience=nil,
player_position=nil,
plus_minus=NbaStats::Constants::NO,
rank=NbaStats::Constants::NO,
season_segment=nil,
starter_bench=nil,
vs_conference=nil,
vs_division=nil,
season_type=NbaStats::Constants::SEASON_TYPE_REGULAR,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::LeagueDashTeamStats.new(
get(LEAGUE_DASH_TEAM_STATS_PATH, {
:DateFrom => date_from,
:DateTo => date_to,
:GameScope => game_scope,
:GameSegment => game_segment,
:LastNGames => last_n_games,
:LeagueID => league_id,
:Location => location,
:MeasureType => measure_type,
:Month => month,
:OpponentTeamID => opponent_team_id,
:Outcome => outcome,
:PaceAdjust => pace_adjust,
:PerMode => per_mode,
:Period => period,
:PlayerExperience => player_experience,
:PlayerPosition => player_position,
:PlusMinus => plus_minus,
:Rank => rank,
:Season => season,
:SeasonSegment => season_segment,
:SeasonType => season_type,
:StarterBench => starter_bench,
:VsConference => vs_conference,
:VsDivision => vs_division
})
)
end | ruby | def league_dash_team_stats(
season,
date_from=nil,
date_to=nil,
game_scope=nil,
game_segment=nil,
last_n_games=0,
location=nil,
measure_type=NbaStats::Constants::MEASURE_TYPE_BASE,
month=0,
opponent_team_id=0,
outcome=nil,
pace_adjust=NbaStats::Constants::NO,
per_mode=NbaStats::Constants::PER_MODE_GAME,
period=0,
player_experience=nil,
player_position=nil,
plus_minus=NbaStats::Constants::NO,
rank=NbaStats::Constants::NO,
season_segment=nil,
starter_bench=nil,
vs_conference=nil,
vs_division=nil,
season_type=NbaStats::Constants::SEASON_TYPE_REGULAR,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::LeagueDashTeamStats.new(
get(LEAGUE_DASH_TEAM_STATS_PATH, {
:DateFrom => date_from,
:DateTo => date_to,
:GameScope => game_scope,
:GameSegment => game_segment,
:LastNGames => last_n_games,
:LeagueID => league_id,
:Location => location,
:MeasureType => measure_type,
:Month => month,
:OpponentTeamID => opponent_team_id,
:Outcome => outcome,
:PaceAdjust => pace_adjust,
:PerMode => per_mode,
:Period => period,
:PlayerExperience => player_experience,
:PlayerPosition => player_position,
:PlusMinus => plus_minus,
:Rank => rank,
:Season => season,
:SeasonSegment => season_segment,
:SeasonType => season_type,
:StarterBench => starter_bench,
:VsConference => vs_conference,
:VsDivision => vs_division
})
)
end | [
"def",
"league_dash_team_stats",
"(",
"season",
",",
"date_from",
"=",
"nil",
",",
"date_to",
"=",
"nil",
",",
"game_scope",
"=",
"nil",
",",
"game_segment",
"=",
"nil",
",",
"last_n_games",
"=",
"0",
",",
"location",
"=",
"nil",
",",
"measure_type",
"=",
"NbaStats",
"::",
"Constants",
"::",
"MEASURE_TYPE_BASE",
",",
"month",
"=",
"0",
",",
"opponent_team_id",
"=",
"0",
",",
"outcome",
"=",
"nil",
",",
"pace_adjust",
"=",
"NbaStats",
"::",
"Constants",
"::",
"NO",
",",
"per_mode",
"=",
"NbaStats",
"::",
"Constants",
"::",
"PER_MODE_GAME",
",",
"period",
"=",
"0",
",",
"player_experience",
"=",
"nil",
",",
"player_position",
"=",
"nil",
",",
"plus_minus",
"=",
"NbaStats",
"::",
"Constants",
"::",
"NO",
",",
"rank",
"=",
"NbaStats",
"::",
"Constants",
"::",
"NO",
",",
"season_segment",
"=",
"nil",
",",
"starter_bench",
"=",
"nil",
",",
"vs_conference",
"=",
"nil",
",",
"vs_division",
"=",
"nil",
",",
"season_type",
"=",
"NbaStats",
"::",
"Constants",
"::",
"SEASON_TYPE_REGULAR",
",",
"league_id",
"=",
"NbaStats",
"::",
"Constants",
"::",
"LEAGUE_ID_NBA",
")",
"NbaStats",
"::",
"Resources",
"::",
"LeagueDashTeamStats",
".",
"new",
"(",
"get",
"(",
"LEAGUE_DASH_TEAM_STATS_PATH",
",",
"{",
":DateFrom",
"=>",
"date_from",
",",
":DateTo",
"=>",
"date_to",
",",
":GameScope",
"=>",
"game_scope",
",",
":GameSegment",
"=>",
"game_segment",
",",
":LastNGames",
"=>",
"last_n_games",
",",
":LeagueID",
"=>",
"league_id",
",",
":Location",
"=>",
"location",
",",
":MeasureType",
"=>",
"measure_type",
",",
":Month",
"=>",
"month",
",",
":OpponentTeamID",
"=>",
"opponent_team_id",
",",
":Outcome",
"=>",
"outcome",
",",
":PaceAdjust",
"=>",
"pace_adjust",
",",
":PerMode",
"=>",
"per_mode",
",",
":Period",
"=>",
"period",
",",
":PlayerExperience",
"=>",
"player_experience",
",",
":PlayerPosition",
"=>",
"player_position",
",",
":PlusMinus",
"=>",
"plus_minus",
",",
":Rank",
"=>",
"rank",
",",
":Season",
"=>",
"season",
",",
":SeasonSegment",
"=>",
"season_segment",
",",
":SeasonType",
"=>",
"season_type",
",",
":StarterBench",
"=>",
"starter_bench",
",",
":VsConference",
"=>",
"vs_conference",
",",
":VsDivision",
"=>",
"vs_division",
"}",
")",
")",
"end"
] | Calls the leaguedashteamstats API and returns a LeagueDashTeamStats resource.
@param date_from [Date]
@param date_to [Date]
@param game_scope [String]
@param game_segment [String]
@param last_n_games [Integer]
@param league_id [String]
@param location [String]
@param measure_type [String]
@param month [Integer]
@param opponent_team_id [String]
@param outcome [String]
@param pace_adjust [String]
@param per_mode [String]
@param period [Integer]
@param player_experience [String]
@param player_position [String]
@param plus_minus [String]
@param rank [String]
@param season [String]
@param season_segment [String]
@param season_type [String]
@param starter_bench [String]
@param vs_conference [String]
@param vs_division [String]
@return [NbaStats::Resources::LeagueDashTeamStats] | [
"Calls",
"the",
"leaguedashteamstats",
"API",
"and",
"returns",
"a",
"LeagueDashTeamStats",
"resource",
"."
] | d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa | https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/league_dash_team_stats.rb#L37-L91 | train |
dagrz/nba_stats | lib/nba_stats/stats/player_game_log.rb | NbaStats.PlayerGameLog.player_game_log | def player_game_log(
player_id,
season,
season_type=NbaStats::Constants::SEASON_TYPE_REGULAR,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::PlayerGameLog.new(
get(PLAYER_GAME_LOG_PATH, {
:Season => season,
:LeagueID => league_id,
:PlayerID => player_id,
:SeasonType => season_type
})
)
end | ruby | def player_game_log(
player_id,
season,
season_type=NbaStats::Constants::SEASON_TYPE_REGULAR,
league_id=NbaStats::Constants::LEAGUE_ID_NBA
)
NbaStats::Resources::PlayerGameLog.new(
get(PLAYER_GAME_LOG_PATH, {
:Season => season,
:LeagueID => league_id,
:PlayerID => player_id,
:SeasonType => season_type
})
)
end | [
"def",
"player_game_log",
"(",
"player_id",
",",
"season",
",",
"season_type",
"=",
"NbaStats",
"::",
"Constants",
"::",
"SEASON_TYPE_REGULAR",
",",
"league_id",
"=",
"NbaStats",
"::",
"Constants",
"::",
"LEAGUE_ID_NBA",
")",
"NbaStats",
"::",
"Resources",
"::",
"PlayerGameLog",
".",
"new",
"(",
"get",
"(",
"PLAYER_GAME_LOG_PATH",
",",
"{",
":Season",
"=>",
"season",
",",
":LeagueID",
"=>",
"league_id",
",",
":PlayerID",
"=>",
"player_id",
",",
":SeasonType",
"=>",
"season_type",
"}",
")",
")",
"end"
] | Calls the playergamelog API and returns a PlayerGameLog resource.
@param league_id [String]
@param player_id [Integer]
@param season [String]
@param season_type [String]
@return [NbaStats::Resources::PlayerGameLog] | [
"Calls",
"the",
"playergamelog",
"API",
"and",
"returns",
"a",
"PlayerGameLog",
"resource",
"."
] | d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa | https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/player_game_log.rb#L17-L31 | train |
dcuddeback/rspec-tag_matchers | lib/rspec/tag_matchers/multiple_input_matcher.rb | RSpec::TagMatchers.MultipleInputMatcher.matches? | def matches?(rendered)
@rendered = rendered
@failures = matchers.reject do |matcher|
matcher.matches?(rendered)
end
@failures.empty?
end | ruby | def matches?(rendered)
@rendered = rendered
@failures = matchers.reject do |matcher|
matcher.matches?(rendered)
end
@failures.empty?
end | [
"def",
"matches?",
"(",
"rendered",
")",
"@rendered",
"=",
"rendered",
"@failures",
"=",
"matchers",
".",
"reject",
"do",
"|",
"matcher",
"|",
"matcher",
".",
"matches?",
"(",
"rendered",
")",
"end",
"@failures",
".",
"empty?",
"end"
] | Initializes a matcher that matches multiple input elements.
@param [Hash] components A hash of matchers. The keys should be the keys used in Rails'
multi-parameter assignment, e.g., <tt>"1i"</tt>, <tt>"2s"</tt>, etc,
and the values are the matchers that must be satisfied.
Tests whether the matcher matches the +rendered+ string. It delegates matching to its
matchers. It returns true if all of its matchers return true. It returns false if *any* of its
matchers return false.
@param [String] rendered A string of HTML or an Object whose +to_s+ method returns HTML.
(That includes Nokogiri classes.)
@return [Boolean] | [
"Initializes",
"a",
"matcher",
"that",
"matches",
"multiple",
"input",
"elements",
"."
] | 6396a833d99ea669699afb1b3dfc62c4512c8882 | https://github.com/dcuddeback/rspec-tag_matchers/blob/6396a833d99ea669699afb1b3dfc62c4512c8882/lib/rspec/tag_matchers/multiple_input_matcher.rb#L44-L51 | train |
dcuddeback/rspec-tag_matchers | lib/rspec/tag_matchers/multiple_input_matcher.rb | RSpec::TagMatchers.MultipleInputMatcher.for | def for(*args)
@for = args.dup
@for.extend(DeepFlattening)
@for = @for.deep_flatten
@components.each do |index, matcher|
delegated_for(index, matcher, @for)
end
self
end | ruby | def for(*args)
@for = args.dup
@for.extend(DeepFlattening)
@for = @for.deep_flatten
@components.each do |index, matcher|
delegated_for(index, matcher, @for)
end
self
end | [
"def",
"for",
"(",
"*",
"args",
")",
"@for",
"=",
"args",
".",
"dup",
"@for",
".",
"extend",
"(",
"DeepFlattening",
")",
"@for",
"=",
"@for",
".",
"deep_flatten",
"@components",
".",
"each",
"do",
"|",
"index",
",",
"matcher",
"|",
"delegated_for",
"(",
"index",
",",
"matcher",
",",
"@for",
")",
"end",
"self",
"end"
] | Specifies the inputs' names with more accuracy than the default regular expressions. It
delegates to each matcher's +for+ method. But it first appends the matcher's key to the last
component of the input's name.
@example Input naming delegation
hour_matcher = HasSelect.new
minute_matcher = HasSelect.new
time_matcher = MultipleInputMatcher.new('4i' => hour_matcher, '5i' => minute_matcher)
time_matcher.for(:event => :start_time) # calls hour_matcher.for("event", "start_time(4i)")
# and minute_matcher.for("event", "start_time(5i)")
@param [Array, Hash] args A hierarchy of string that specify the attribute name.
@return [MultipleInputMatcher] self | [
"Specifies",
"the",
"inputs",
"names",
"with",
"more",
"accuracy",
"than",
"the",
"default",
"regular",
"expressions",
".",
"It",
"delegates",
"to",
"each",
"matcher",
"s",
"+",
"for",
"+",
"method",
".",
"But",
"it",
"first",
"appends",
"the",
"matcher",
"s",
"key",
"to",
"the",
"last",
"component",
"of",
"the",
"input",
"s",
"name",
"."
] | 6396a833d99ea669699afb1b3dfc62c4512c8882 | https://github.com/dcuddeback/rspec-tag_matchers/blob/6396a833d99ea669699afb1b3dfc62c4512c8882/lib/rspec/tag_matchers/multiple_input_matcher.rb#L68-L77 | train |
dcuddeback/rspec-tag_matchers | lib/rspec/tag_matchers/multiple_input_matcher.rb | RSpec::TagMatchers.MultipleInputMatcher.delegated_for | def delegated_for(key, matcher, args)
args = args.dup
args[-1] = args[-1].to_s
args[-1] += "(#{key})"
matcher.for(*args)
end | ruby | def delegated_for(key, matcher, args)
args = args.dup
args[-1] = args[-1].to_s
args[-1] += "(#{key})"
matcher.for(*args)
end | [
"def",
"delegated_for",
"(",
"key",
",",
"matcher",
",",
"args",
")",
"args",
"=",
"args",
".",
"dup",
"args",
"[",
"-",
"1",
"]",
"=",
"args",
"[",
"-",
"1",
"]",
".",
"to_s",
"args",
"[",
"-",
"1",
"]",
"+=",
"\"(#{key})\"",
"matcher",
".",
"for",
"(",
"*",
"args",
")",
"end"
] | Set's +matcher+'s input name according to +args+ and +key+.
@param [String] key The matcher's key.
@param [HasInput] matcher The matcher.
@param [Arrah, Hash] args A hierarchy of names that would normally be passed to
{HasInput#for}. | [
"Set",
"s",
"+",
"matcher",
"+",
"s",
"input",
"name",
"according",
"to",
"+",
"args",
"+",
"and",
"+",
"key",
"+",
"."
] | 6396a833d99ea669699afb1b3dfc62c4512c8882 | https://github.com/dcuddeback/rspec-tag_matchers/blob/6396a833d99ea669699afb1b3dfc62c4512c8882/lib/rspec/tag_matchers/multiple_input_matcher.rb#L108-L113 | train |
coderanger/dco | lib/dco/cli.rb | Dco.CLI.assert_repo! | def assert_repo!
begin
# Check if the repo fails to load at all.
repo
rescue Exception
raise Thor::Error.new("#{repo_path} does not appear to be a git repository")
end
unless repo.repo.writable?
raise Thor::Error.new("Git repository at #{repo.repo.path} is read-only")
end
end | ruby | def assert_repo!
begin
# Check if the repo fails to load at all.
repo
rescue Exception
raise Thor::Error.new("#{repo_path} does not appear to be a git repository")
end
unless repo.repo.writable?
raise Thor::Error.new("Git repository at #{repo.repo.path} is read-only")
end
end | [
"def",
"assert_repo!",
"begin",
"repo",
"rescue",
"Exception",
"raise",
"Thor",
"::",
"Error",
".",
"new",
"(",
"\"#{repo_path} does not appear to be a git repository\"",
")",
"end",
"unless",
"repo",
".",
"repo",
".",
"writable?",
"raise",
"Thor",
"::",
"Error",
".",
"new",
"(",
"\"Git repository at #{repo.repo.path} is read-only\"",
")",
"end",
"end"
] | Check that we are in a git repo that we have write access to.
@api private
@return [void] | [
"Check",
"that",
"we",
"are",
"in",
"a",
"git",
"repo",
"that",
"we",
"have",
"write",
"access",
"to",
"."
] | a18d60bd9217bcf08f3c264080752f64d855ec39 | https://github.com/coderanger/dco/blob/a18d60bd9217bcf08f3c264080752f64d855ec39/lib/dco/cli.rb#L328-L338 | train |
coderanger/dco | lib/dco/cli.rb | Dco.CLI.current_branch | def current_branch
repo.current_branch.tap {|b| raise Thor::Error.new("No explicit branch passed and current head looks detached: #{b}") if b[0] == '(' }
end | ruby | def current_branch
repo.current_branch.tap {|b| raise Thor::Error.new("No explicit branch passed and current head looks detached: #{b}") if b[0] == '(' }
end | [
"def",
"current_branch",
"repo",
".",
"current_branch",
".",
"tap",
"{",
"|",
"b",
"|",
"raise",
"Thor",
"::",
"Error",
".",
"new",
"(",
"\"No explicit branch passed and current head looks detached: #{b}\"",
")",
"if",
"b",
"[",
"0",
"]",
"==",
"'('",
"}",
"end"
] | Get the current branch but raise an error if it looks like we're on a detched head.
@api private
@return [String] | [
"Get",
"the",
"current",
"branch",
"but",
"raise",
"an",
"error",
"if",
"it",
"looks",
"like",
"we",
"re",
"on",
"a",
"detched",
"head",
"."
] | a18d60bd9217bcf08f3c264080752f64d855ec39 | https://github.com/coderanger/dco/blob/a18d60bd9217bcf08f3c264080752f64d855ec39/lib/dco/cli.rb#L360-L362 | train |
coderanger/dco | lib/dco/cli.rb | Dco.CLI.has_sign_off? | def has_sign_off?(commit_or_message)
message = commit_or_message.is_a?(String) ? commit_or_message : commit_or_message.message
if message =~ /^Signed-off-by: (.+)$/
$1
else
nil
end
end | ruby | def has_sign_off?(commit_or_message)
message = commit_or_message.is_a?(String) ? commit_or_message : commit_or_message.message
if message =~ /^Signed-off-by: (.+)$/
$1
else
nil
end
end | [
"def",
"has_sign_off?",
"(",
"commit_or_message",
")",
"message",
"=",
"commit_or_message",
".",
"is_a?",
"(",
"String",
")",
"?",
"commit_or_message",
":",
"commit_or_message",
".",
"message",
"if",
"message",
"=~",
"/",
"/",
"$1",
"else",
"nil",
"end",
"end"
] | Check if a commit or commit message is already signed off.
@api private
@param commit_or_message [String, Git::Commit] Commit object or message string.
@return [String, nil] | [
"Check",
"if",
"a",
"commit",
"or",
"commit",
"message",
"is",
"already",
"signed",
"off",
"."
] | a18d60bd9217bcf08f3c264080752f64d855ec39 | https://github.com/coderanger/dco/blob/a18d60bd9217bcf08f3c264080752f64d855ec39/lib/dco/cli.rb#L394-L401 | train |
sawaken/ruby-binary-parser | lib/binary_parser/general_class/abstract_binary.rb | BinaryParser.AbstractBinary.alt | def alt(binary_or_uint)
case binary_or_uint
when Integer
alt_uint(binary_or_uint)
when String
alt_binary(binary_or_uint)
else
raise BadManipulationError, "Argument shouled be Integer or binary-encoded String."
end
end | ruby | def alt(binary_or_uint)
case binary_or_uint
when Integer
alt_uint(binary_or_uint)
when String
alt_binary(binary_or_uint)
else
raise BadManipulationError, "Argument shouled be Integer or binary-encoded String."
end
end | [
"def",
"alt",
"(",
"binary_or_uint",
")",
"case",
"binary_or_uint",
"when",
"Integer",
"alt_uint",
"(",
"binary_or_uint",
")",
"when",
"String",
"alt_binary",
"(",
"binary_or_uint",
")",
"else",
"raise",
"BadManipulationError",
",",
"\"Argument shouled be Integer or binary-encoded String.\"",
"end",
"end"
] | Methods for generating modified binary. | [
"Methods",
"for",
"generating",
"modified",
"binary",
"."
] | c9ae043915d1a91677a2296e2f15d2929242d8f7 | https://github.com/sawaken/ruby-binary-parser/blob/c9ae043915d1a91677a2296e2f15d2929242d8f7/lib/binary_parser/general_class/abstract_binary.rb#L44-L53 | train |
domitry/mikon | lib/mikon/core/dataframe.rb | Mikon.DataFrame.[] | def [](arg)
case
when arg.is_a?(Range)
index = @index.select{|i| arg.include?(i)}
Mikon::DataFrame.new(index.map{|i| self.row(i)}, {index: index})
when arg.is_a?(Symbol)
self.column(arg)
end
end | ruby | def [](arg)
case
when arg.is_a?(Range)
index = @index.select{|i| arg.include?(i)}
Mikon::DataFrame.new(index.map{|i| self.row(i)}, {index: index})
when arg.is_a?(Symbol)
self.column(arg)
end
end | [
"def",
"[]",
"(",
"arg",
")",
"case",
"when",
"arg",
".",
"is_a?",
"(",
"Range",
")",
"index",
"=",
"@index",
".",
"select",
"{",
"|",
"i",
"|",
"arg",
".",
"include?",
"(",
"i",
")",
"}",
"Mikon",
"::",
"DataFrame",
".",
"new",
"(",
"index",
".",
"map",
"{",
"|",
"i",
"|",
"self",
".",
"row",
"(",
"i",
")",
"}",
",",
"{",
"index",
":",
"index",
"}",
")",
"when",
"arg",
".",
"is_a?",
"(",
"Symbol",
")",
"self",
".",
"column",
"(",
"arg",
")",
"end",
"end"
] | Accessor for column and rows
@example
df = DataFrame.new({a: [1, 2, 3], b: [2, 3, 4]})
df[0..1].to_json #-> {a: [1, 2], b: [2, 3]}
df[:a] #-> <Mikon::Series> | [
"Accessor",
"for",
"column",
"and",
"rows"
] | 69886f5b6767d141e0a5624f0de2f34743909537 | https://github.com/domitry/mikon/blob/69886f5b6767d141e0a5624f0de2f34743909537/lib/mikon/core/dataframe.rb#L140-L149 | train |
domitry/mikon | lib/mikon/core/dataframe.rb | Mikon.DataFrame.column | def column(label)
pos = @labels.index(label)
raise "There is no column named " + label if pos.nil?
Mikon::Series.new(label, @data[pos], index: @index)
end | ruby | def column(label)
pos = @labels.index(label)
raise "There is no column named " + label if pos.nil?
Mikon::Series.new(label, @data[pos], index: @index)
end | [
"def",
"column",
"(",
"label",
")",
"pos",
"=",
"@labels",
".",
"index",
"(",
"label",
")",
"raise",
"\"There is no column named \"",
"+",
"label",
"if",
"pos",
".",
"nil?",
"Mikon",
"::",
"Series",
".",
"new",
"(",
"label",
",",
"@data",
"[",
"pos",
"]",
",",
"index",
":",
"@index",
")",
"end"
] | Access column with its name | [
"Access",
"column",
"with",
"its",
"name"
] | 69886f5b6767d141e0a5624f0de2f34743909537 | https://github.com/domitry/mikon/blob/69886f5b6767d141e0a5624f0de2f34743909537/lib/mikon/core/dataframe.rb#L152-L156 | train |
domitry/mikon | lib/mikon/core/dataframe.rb | Mikon.DataFrame.to_html | def to_html(threshold=50)
html = "<html><table><tr><td></td>"
html += @labels.map{|label| "<th>" + label.to_s + "</th>"}.join
html += "</tr>"
self.each_row.with_index do |row, pos|
next if pos > threshold && pos != self.length-1
html += "<tr><th>" + @index[pos].to_s + "</th>"
html += @labels.map{|label| "<td>" + row[label].to_s + "</td>"}.join
html += "</tr>"
html += "<tr><th>...</th>" + "<td>...</td>"*@labels.length + "</tr>" if pos == threshold
end
html += "</table>"
end | ruby | def to_html(threshold=50)
html = "<html><table><tr><td></td>"
html += @labels.map{|label| "<th>" + label.to_s + "</th>"}.join
html += "</tr>"
self.each_row.with_index do |row, pos|
next if pos > threshold && pos != self.length-1
html += "<tr><th>" + @index[pos].to_s + "</th>"
html += @labels.map{|label| "<td>" + row[label].to_s + "</td>"}.join
html += "</tr>"
html += "<tr><th>...</th>" + "<td>...</td>"*@labels.length + "</tr>" if pos == threshold
end
html += "</table>"
end | [
"def",
"to_html",
"(",
"threshold",
"=",
"50",
")",
"html",
"=",
"\"<html><table><tr><td></td>\"",
"html",
"+=",
"@labels",
".",
"map",
"{",
"|",
"label",
"|",
"\"<th>\"",
"+",
"label",
".",
"to_s",
"+",
"\"</th>\"",
"}",
".",
"join",
"html",
"+=",
"\"</tr>\"",
"self",
".",
"each_row",
".",
"with_index",
"do",
"|",
"row",
",",
"pos",
"|",
"next",
"if",
"pos",
">",
"threshold",
"&&",
"pos",
"!=",
"self",
".",
"length",
"-",
"1",
"html",
"+=",
"\"<tr><th>\"",
"+",
"@index",
"[",
"pos",
"]",
".",
"to_s",
"+",
"\"</th>\"",
"html",
"+=",
"@labels",
".",
"map",
"{",
"|",
"label",
"|",
"\"<td>\"",
"+",
"row",
"[",
"label",
"]",
".",
"to_s",
"+",
"\"</td>\"",
"}",
".",
"join",
"html",
"+=",
"\"</tr>\"",
"html",
"+=",
"\"<tr><th>...</th>\"",
"+",
"\"<td>...</td>\"",
"*",
"@labels",
".",
"length",
"+",
"\"</tr>\"",
"if",
"pos",
"==",
"threshold",
"end",
"html",
"+=",
"\"</table>\"",
"end"
] | IRuby notebook automatically call this method | [
"IRuby",
"notebook",
"automatically",
"call",
"this",
"method"
] | 69886f5b6767d141e0a5624f0de2f34743909537 | https://github.com/domitry/mikon/blob/69886f5b6767d141e0a5624f0de2f34743909537/lib/mikon/core/dataframe.rb#L179-L191 | train |
domitry/mikon | lib/mikon/core/dataframe.rb | Mikon.DataFrame.sort | def sort(label, ascending=true)
i = @labels.index(label)
raise "No column named" + label.to_s if i.nil?
order = @data[i].sorted_indices
order.reverse! unless ascending
self.sort_by.with_index{|val, i| order.index(i)}
end | ruby | def sort(label, ascending=true)
i = @labels.index(label)
raise "No column named" + label.to_s if i.nil?
order = @data[i].sorted_indices
order.reverse! unless ascending
self.sort_by.with_index{|val, i| order.index(i)}
end | [
"def",
"sort",
"(",
"label",
",",
"ascending",
"=",
"true",
")",
"i",
"=",
"@labels",
".",
"index",
"(",
"label",
")",
"raise",
"\"No column named\"",
"+",
"label",
".",
"to_s",
"if",
"i",
".",
"nil?",
"order",
"=",
"@data",
"[",
"i",
"]",
".",
"sorted_indices",
"order",
".",
"reverse!",
"unless",
"ascending",
"self",
".",
"sort_by",
".",
"with_index",
"{",
"|",
"val",
",",
"i",
"|",
"order",
".",
"index",
"(",
"i",
")",
"}",
"end"
] | Sort by label
@param [Symbol] label column name to sort by
@param [Bool] ascending default true | [
"Sort",
"by",
"label"
] | 69886f5b6767d141e0a5624f0de2f34743909537 | https://github.com/domitry/mikon/blob/69886f5b6767d141e0a5624f0de2f34743909537/lib/mikon/core/dataframe.rb#L273-L279 | train |
domitry/mikon | lib/mikon/core/dataframe.rb | Mikon.DataFrame.row | def row(index)
pos = @index.index(index)
arr = @data.map{|column| column[pos]}
Mikon::Row.new(@labels, arr, index)
end | ruby | def row(index)
pos = @index.index(index)
arr = @data.map{|column| column[pos]}
Mikon::Row.new(@labels, arr, index)
end | [
"def",
"row",
"(",
"index",
")",
"pos",
"=",
"@index",
".",
"index",
"(",
"index",
")",
"arr",
"=",
"@data",
".",
"map",
"{",
"|",
"column",
"|",
"column",
"[",
"pos",
"]",
"}",
"Mikon",
"::",
"Row",
".",
"new",
"(",
"@labels",
",",
"arr",
",",
"index",
")",
"end"
] | Access row using index | [
"Access",
"row",
"using",
"index"
] | 69886f5b6767d141e0a5624f0de2f34743909537 | https://github.com/domitry/mikon/blob/69886f5b6767d141e0a5624f0de2f34743909537/lib/mikon/core/dataframe.rb#L327-L331 | train |
opulent/opulent | lib/opulent/parser/yield.rb | Opulent.Parser.block_yield | def block_yield(parent, indent)
return unless accept :yield
# Consume the newline from the end of the element
error :yield unless accept(:line_feed).strip.empty?
# Create a new node
yield_node = [:yield, nil, {}, [], indent]
parent[@children] << yield_node
end | ruby | def block_yield(parent, indent)
return unless accept :yield
# Consume the newline from the end of the element
error :yield unless accept(:line_feed).strip.empty?
# Create a new node
yield_node = [:yield, nil, {}, [], indent]
parent[@children] << yield_node
end | [
"def",
"block_yield",
"(",
"parent",
",",
"indent",
")",
"return",
"unless",
"accept",
":yield",
"error",
":yield",
"unless",
"accept",
"(",
":line_feed",
")",
".",
"strip",
".",
"empty?",
"yield_node",
"=",
"[",
":yield",
",",
"nil",
",",
"{",
"}",
",",
"[",
"]",
",",
"indent",
"]",
"parent",
"[",
"@children",
"]",
"<<",
"yield_node",
"end"
] | Match a yield with a explicit or implicit target
yield target
@param parent [Node] Parent node to which we append the definition | [
"Match",
"a",
"yield",
"with",
"a",
"explicit",
"or",
"implicit",
"target"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/yield.rb#L11-L21 | train |
Yellowen/Faalis | lib/faalis/dashboard/sections/resource_create.rb | Faalis::Dashboard::Sections.ResourceCreate.create | def create
authorize model
@resource = model.new(creation_params)
@resource.assign_attributes(**reflections_hash) unless reflections_hash.nil?
# Customize the create behaviour
before_create_hook(@resource)
# TODO: Handle M2M relations in here
if @resource.save
after_create_hook(@resource)
successful_response(:create)
else
errorful_resopnse(:create, @resource.errors) do
redirect_to Rails.application.routes.url_helpers.send(@new_route)
end
end
end | ruby | def create
authorize model
@resource = model.new(creation_params)
@resource.assign_attributes(**reflections_hash) unless reflections_hash.nil?
# Customize the create behaviour
before_create_hook(@resource)
# TODO: Handle M2M relations in here
if @resource.save
after_create_hook(@resource)
successful_response(:create)
else
errorful_resopnse(:create, @resource.errors) do
redirect_to Rails.application.routes.url_helpers.send(@new_route)
end
end
end | [
"def",
"create",
"authorize",
"model",
"@resource",
"=",
"model",
".",
"new",
"(",
"creation_params",
")",
"@resource",
".",
"assign_attributes",
"(",
"**",
"reflections_hash",
")",
"unless",
"reflections_hash",
".",
"nil?",
"before_create_hook",
"(",
"@resource",
")",
"if",
"@resource",
".",
"save",
"after_create_hook",
"(",
"@resource",
")",
"successful_response",
"(",
":create",
")",
"else",
"errorful_resopnse",
"(",
":create",
",",
"@resource",
".",
"errors",
")",
"do",
"redirect_to",
"Rails",
".",
"application",
".",
"routes",
".",
"url_helpers",
".",
"send",
"(",
"@new_route",
")",
"end",
"end",
"end"
] | The actual action method for creating new resource. | [
"The",
"actual",
"action",
"method",
"for",
"creating",
"new",
"resource",
"."
] | d12abdb8559dabbf6b2044e3ba437038527039b2 | https://github.com/Yellowen/Faalis/blob/d12abdb8559dabbf6b2044e3ba437038527039b2/lib/faalis/dashboard/sections/resource_create.rb#L71-L89 | train |
Yellowen/Faalis | lib/faalis/dashboard/sections/resource_create.rb | Faalis::Dashboard::Sections.ResourceCreate.is_reflection? | def is_reflection?(c)
has_many = ActiveRecord::Reflection::HasManyReflection
has_and_belongs_to_many = ActiveRecord::Reflection::HasAndBelongsToManyReflection
has_many_through = ActiveRecord::Reflection::ThroughReflection
result = c.is_a?(has_many) || c.is_a?(has_and_belongs_to_many)
result || c.is_a?(has_many_through)
end | ruby | def is_reflection?(c)
has_many = ActiveRecord::Reflection::HasManyReflection
has_and_belongs_to_many = ActiveRecord::Reflection::HasAndBelongsToManyReflection
has_many_through = ActiveRecord::Reflection::ThroughReflection
result = c.is_a?(has_many) || c.is_a?(has_and_belongs_to_many)
result || c.is_a?(has_many_through)
end | [
"def",
"is_reflection?",
"(",
"c",
")",
"has_many",
"=",
"ActiveRecord",
"::",
"Reflection",
"::",
"HasManyReflection",
"has_and_belongs_to_many",
"=",
"ActiveRecord",
"::",
"Reflection",
"::",
"HasAndBelongsToManyReflection",
"has_many_through",
"=",
"ActiveRecord",
"::",
"Reflection",
"::",
"ThroughReflection",
"result",
"=",
"c",
".",
"is_a?",
"(",
"has_many",
")",
"||",
"c",
".",
"is_a?",
"(",
"has_and_belongs_to_many",
")",
"result",
"||",
"c",
".",
"is_a?",
"(",
"has_many_through",
")",
"end"
] | Check whether the given column is a reflection or not. | [
"Check",
"whether",
"the",
"given",
"column",
"is",
"a",
"reflection",
"or",
"not",
"."
] | d12abdb8559dabbf6b2044e3ba437038527039b2 | https://github.com/Yellowen/Faalis/blob/d12abdb8559dabbf6b2044e3ba437038527039b2/lib/faalis/dashboard/sections/resource_create.rb#L126-L133 | train |
platanus/dialers | lib/dialers/transformable.rb | Dialers.Transformable.transform_to_one | def transform_to_one(entity_class_or_decider, root: nil)
object = root ? raw_data[root] : raw_data
transform_attributes_to_object(entity_class_or_decider, object)
end | ruby | def transform_to_one(entity_class_or_decider, root: nil)
object = root ? raw_data[root] : raw_data
transform_attributes_to_object(entity_class_or_decider, object)
end | [
"def",
"transform_to_one",
"(",
"entity_class_or_decider",
",",
"root",
":",
"nil",
")",
"object",
"=",
"root",
"?",
"raw_data",
"[",
"root",
"]",
":",
"raw_data",
"transform_attributes_to_object",
"(",
"entity_class_or_decider",
",",
"object",
")",
"end"
] | Transforms a response into one object based on the response's body.
If you pass a hash like this:
{ 200 => ProductCreated, 202 => ProductAccepted }
the transformation will decide which object to create based on the status.
It's important to note that the class must provide attribute writers for this method to be
able to fill an object with the responses's body data.
@param entity_class_or_decider [Hash, Class] A class or a hash of Fixnum => Class
to decide with the status.
@param root [String, nil] The root to use to get the object from the body.
@return [Object] The result of the transformation. | [
"Transforms",
"a",
"response",
"into",
"one",
"object",
"based",
"on",
"the",
"response",
"s",
"body",
"."
] | 8fd8750c367ec0d058d2adfe25915125d95cb890 | https://github.com/platanus/dialers/blob/8fd8750c367ec0d058d2adfe25915125d95cb890/lib/dialers/transformable.rb#L28-L31 | train |
platanus/dialers | lib/dialers/transformable.rb | Dialers.Transformable.transform_to_many | def transform_to_many(entity_class_or_decider, root: nil)
items = get_rooted_items(root)
unless items.is_a?(Array)
fail Dialers::ImpossibleTranformationError.new(response)
end
items.map { |item| transform_attributes_to_object(entity_class_or_decider, item) }
end | ruby | def transform_to_many(entity_class_or_decider, root: nil)
items = get_rooted_items(root)
unless items.is_a?(Array)
fail Dialers::ImpossibleTranformationError.new(response)
end
items.map { |item| transform_attributes_to_object(entity_class_or_decider, item) }
end | [
"def",
"transform_to_many",
"(",
"entity_class_or_decider",
",",
"root",
":",
"nil",
")",
"items",
"=",
"get_rooted_items",
"(",
"root",
")",
"unless",
"items",
".",
"is_a?",
"(",
"Array",
")",
"fail",
"Dialers",
"::",
"ImpossibleTranformationError",
".",
"new",
"(",
"response",
")",
"end",
"items",
".",
"map",
"{",
"|",
"item",
"|",
"transform_attributes_to_object",
"(",
"entity_class_or_decider",
",",
"item",
")",
"}",
"end"
] | Transforms a response into many objects based on the response's body.
@param entity_class_or_decider [Hash, Class] A class or a hash of Fixnum => Class
to decide with the status.
@param root [String, nil] The root to use to get an array from the body.
@return [Array<Object>] The result of the transformation. | [
"Transforms",
"a",
"response",
"into",
"many",
"objects",
"based",
"on",
"the",
"response",
"s",
"body",
"."
] | 8fd8750c367ec0d058d2adfe25915125d95cb890 | https://github.com/platanus/dialers/blob/8fd8750c367ec0d058d2adfe25915125d95cb890/lib/dialers/transformable.rb#L40-L46 | train |
taganaka/polipus | lib/polipus.rb | Polipus.PolipusCrawler.add_url | def add_url(url, params = {})
page = Page.new(url, params)
yield(page) if block_given?
internal_queue << page.to_json
end | ruby | def add_url(url, params = {})
page = Page.new(url, params)
yield(page) if block_given?
internal_queue << page.to_json
end | [
"def",
"add_url",
"(",
"url",
",",
"params",
"=",
"{",
"}",
")",
"page",
"=",
"Page",
".",
"new",
"(",
"url",
",",
"params",
")",
"yield",
"(",
"page",
")",
"if",
"block_given?",
"internal_queue",
"<<",
"page",
".",
"to_json",
"end"
] | Enqueue an url, no matter what | [
"Enqueue",
"an",
"url",
"no",
"matter",
"what"
] | 8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6 | https://github.com/taganaka/polipus/blob/8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6/lib/polipus.rb#L359-L363 | train |
taganaka/polipus | lib/polipus.rb | Polipus.PolipusCrawler.should_be_visited? | def should_be_visited?(url, with_tracker = true)
case
# robots.txt
when !allowed_by_robot?(url)
false
# Check against whitelist pattern matching
when !@follow_links_like.empty? && @follow_links_like.none? { |p| url.path =~ p }
false
# Check against blacklist pattern matching
when @skip_links_like.any? { |p| url.path =~ p }
false
# Page is marked as expired
when page_expired?(Page.new(url))
true
# Check against url tracker
when with_tracker && url_tracker.visited?(@options[:include_query_string_in_saved_page] ? url.to_s : url.to_s.gsub(/\?.*$/, ''))
false
else
true
end
end | ruby | def should_be_visited?(url, with_tracker = true)
case
# robots.txt
when !allowed_by_robot?(url)
false
# Check against whitelist pattern matching
when !@follow_links_like.empty? && @follow_links_like.none? { |p| url.path =~ p }
false
# Check against blacklist pattern matching
when @skip_links_like.any? { |p| url.path =~ p }
false
# Page is marked as expired
when page_expired?(Page.new(url))
true
# Check against url tracker
when with_tracker && url_tracker.visited?(@options[:include_query_string_in_saved_page] ? url.to_s : url.to_s.gsub(/\?.*$/, ''))
false
else
true
end
end | [
"def",
"should_be_visited?",
"(",
"url",
",",
"with_tracker",
"=",
"true",
")",
"case",
"when",
"!",
"allowed_by_robot?",
"(",
"url",
")",
"false",
"when",
"!",
"@follow_links_like",
".",
"empty?",
"&&",
"@follow_links_like",
".",
"none?",
"{",
"|",
"p",
"|",
"url",
".",
"path",
"=~",
"p",
"}",
"false",
"when",
"@skip_links_like",
".",
"any?",
"{",
"|",
"p",
"|",
"url",
".",
"path",
"=~",
"p",
"}",
"false",
"when",
"page_expired?",
"(",
"Page",
".",
"new",
"(",
"url",
")",
")",
"true",
"when",
"with_tracker",
"&&",
"url_tracker",
".",
"visited?",
"(",
"@options",
"[",
":include_query_string_in_saved_page",
"]",
"?",
"url",
".",
"to_s",
":",
"url",
".",
"to_s",
".",
"gsub",
"(",
"/",
"\\?",
"/",
",",
"''",
")",
")",
"false",
"else",
"true",
"end",
"end"
] | URLs enqueue policy | [
"URLs",
"enqueue",
"policy"
] | 8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6 | https://github.com/taganaka/polipus/blob/8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6/lib/polipus.rb#L375-L395 | train |
taganaka/polipus | lib/polipus.rb | Polipus.PolipusCrawler.links_for | def links_for(page)
page.domain_aliases = domain_aliases
@focus_crawl_block.nil? ? page.links : @focus_crawl_block.call(page)
end | ruby | def links_for(page)
page.domain_aliases = domain_aliases
@focus_crawl_block.nil? ? page.links : @focus_crawl_block.call(page)
end | [
"def",
"links_for",
"(",
"page",
")",
"page",
".",
"domain_aliases",
"=",
"domain_aliases",
"@focus_crawl_block",
".",
"nil?",
"?",
"page",
".",
"links",
":",
"@focus_crawl_block",
".",
"call",
"(",
"page",
")",
"end"
] | It extracts URLs from the page | [
"It",
"extracts",
"URLs",
"from",
"the",
"page"
] | 8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6 | https://github.com/taganaka/polipus/blob/8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6/lib/polipus.rb#L398-L401 | train |
taganaka/polipus | lib/polipus.rb | Polipus.PolipusCrawler.page_expired? | def page_expired?(page)
return false if @options[:ttl_page].nil?
stored_page = @storage.get(page)
r = stored_page && stored_page.expired?(@options[:ttl_page])
@logger.debug { "Page #{page.url} marked as expired" } if r
r
end | ruby | def page_expired?(page)
return false if @options[:ttl_page].nil?
stored_page = @storage.get(page)
r = stored_page && stored_page.expired?(@options[:ttl_page])
@logger.debug { "Page #{page.url} marked as expired" } if r
r
end | [
"def",
"page_expired?",
"(",
"page",
")",
"return",
"false",
"if",
"@options",
"[",
":ttl_page",
"]",
".",
"nil?",
"stored_page",
"=",
"@storage",
".",
"get",
"(",
"page",
")",
"r",
"=",
"stored_page",
"&&",
"stored_page",
".",
"expired?",
"(",
"@options",
"[",
":ttl_page",
"]",
")",
"@logger",
".",
"debug",
"{",
"\"Page #{page.url} marked as expired\"",
"}",
"if",
"r",
"r",
"end"
] | whether a page is expired or not | [
"whether",
"a",
"page",
"is",
"expired",
"or",
"not"
] | 8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6 | https://github.com/taganaka/polipus/blob/8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6/lib/polipus.rb#L404-L410 | train |
taganaka/polipus | lib/polipus.rb | Polipus.PolipusCrawler.page_exists? | def page_exists?(page)
return false if page.user_data && page.user_data.p_seeded
@storage.exists?(page) && !page_expired?(page)
end | ruby | def page_exists?(page)
return false if page.user_data && page.user_data.p_seeded
@storage.exists?(page) && !page_expired?(page)
end | [
"def",
"page_exists?",
"(",
"page",
")",
"return",
"false",
"if",
"page",
".",
"user_data",
"&&",
"page",
".",
"user_data",
".",
"p_seeded",
"@storage",
".",
"exists?",
"(",
"page",
")",
"&&",
"!",
"page_expired?",
"(",
"page",
")",
"end"
] | whether a page exists or not | [
"whether",
"a",
"page",
"exists",
"or",
"not"
] | 8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6 | https://github.com/taganaka/polipus/blob/8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6/lib/polipus.rb#L413-L416 | train |
taganaka/polipus | lib/polipus.rb | Polipus.PolipusCrawler.enqueue | def enqueue(url_to_visit, current_page)
page_to_visit = Page.new(url_to_visit.to_s, referer: current_page.url.to_s, depth: current_page.depth + 1)
internal_queue << page_to_visit.to_json
to_track = @options[:include_query_string_in_saved_page] ? url_to_visit.to_s : url_to_visit.to_s.gsub(/\?.*$/, '')
url_tracker.visit to_track
@logger.debug { "Added (#{url_to_visit}) to the queue" }
end | ruby | def enqueue(url_to_visit, current_page)
page_to_visit = Page.new(url_to_visit.to_s, referer: current_page.url.to_s, depth: current_page.depth + 1)
internal_queue << page_to_visit.to_json
to_track = @options[:include_query_string_in_saved_page] ? url_to_visit.to_s : url_to_visit.to_s.gsub(/\?.*$/, '')
url_tracker.visit to_track
@logger.debug { "Added (#{url_to_visit}) to the queue" }
end | [
"def",
"enqueue",
"(",
"url_to_visit",
",",
"current_page",
")",
"page_to_visit",
"=",
"Page",
".",
"new",
"(",
"url_to_visit",
".",
"to_s",
",",
"referer",
":",
"current_page",
".",
"url",
".",
"to_s",
",",
"depth",
":",
"current_page",
".",
"depth",
"+",
"1",
")",
"internal_queue",
"<<",
"page_to_visit",
".",
"to_json",
"to_track",
"=",
"@options",
"[",
":include_query_string_in_saved_page",
"]",
"?",
"url_to_visit",
".",
"to_s",
":",
"url_to_visit",
".",
"to_s",
".",
"gsub",
"(",
"/",
"\\?",
"/",
",",
"''",
")",
"url_tracker",
".",
"visit",
"to_track",
"@logger",
".",
"debug",
"{",
"\"Added (#{url_to_visit}) to the queue\"",
"}",
"end"
] | The url is enqueued for a later visit | [
"The",
"url",
"is",
"enqueued",
"for",
"a",
"later",
"visit"
] | 8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6 | https://github.com/taganaka/polipus/blob/8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6/lib/polipus.rb#L429-L435 | train |
taganaka/polipus | lib/polipus.rb | Polipus.PolipusCrawler.execute_plugin | def execute_plugin(method)
Polipus::Plugin.plugins.each do |k, p|
next unless p.respond_to?(method)
@logger.info { "Running plugin method #{method} on #{k}" }
ret_val = p.send(method, self)
instance_eval(&ret_val) if ret_val.is_a? Proc
end
end | ruby | def execute_plugin(method)
Polipus::Plugin.plugins.each do |k, p|
next unless p.respond_to?(method)
@logger.info { "Running plugin method #{method} on #{k}" }
ret_val = p.send(method, self)
instance_eval(&ret_val) if ret_val.is_a? Proc
end
end | [
"def",
"execute_plugin",
"(",
"method",
")",
"Polipus",
"::",
"Plugin",
".",
"plugins",
".",
"each",
"do",
"|",
"k",
",",
"p",
"|",
"next",
"unless",
"p",
".",
"respond_to?",
"(",
"method",
")",
"@logger",
".",
"info",
"{",
"\"Running plugin method #{method} on #{k}\"",
"}",
"ret_val",
"=",
"p",
".",
"send",
"(",
"method",
",",
"self",
")",
"instance_eval",
"(",
"&",
"ret_val",
")",
"if",
"ret_val",
".",
"is_a?",
"Proc",
"end",
"end"
] | It invokes a plugin method if any | [
"It",
"invokes",
"a",
"plugin",
"method",
"if",
"any"
] | 8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6 | https://github.com/taganaka/polipus/blob/8917a37c151a8e36fcc49fb5461aaeaf97f1f5a6/lib/polipus.rb#L478-L485 | train |
mateomurphy/rails_locale_detection | lib/rails_locale_detection/detection_methods.rb | RailsLocaleDetection.DetectionMethods.set_default_url_option_for_request? | def set_default_url_option_for_request?
RailsLocaleDetection.set_default_url_option === true || RailsLocaleDetection.set_default_url_option == :always || RailsLocaleDetection.set_default_url_option == :explicitly && params[locale_key].present?
end | ruby | def set_default_url_option_for_request?
RailsLocaleDetection.set_default_url_option === true || RailsLocaleDetection.set_default_url_option == :always || RailsLocaleDetection.set_default_url_option == :explicitly && params[locale_key].present?
end | [
"def",
"set_default_url_option_for_request?",
"RailsLocaleDetection",
".",
"set_default_url_option",
"===",
"true",
"||",
"RailsLocaleDetection",
".",
"set_default_url_option",
"==",
":always",
"||",
"RailsLocaleDetection",
".",
"set_default_url_option",
"==",
":explicitly",
"&&",
"params",
"[",
"locale_key",
"]",
".",
"present?",
"end"
] | returns true if the default url option should be set for this request | [
"returns",
"true",
"if",
"the",
"default",
"url",
"option",
"should",
"be",
"set",
"for",
"this",
"request"
] | 0c7748db7374196ca0b5f6aa12aea339671fe704 | https://github.com/mateomurphy/rails_locale_detection/blob/0c7748db7374196ca0b5f6aa12aea339671fe704/lib/rails_locale_detection/detection_methods.rb#L50-L52 | train |
Yellowen/Faalis | app/models/faalis/user.rb | Faalis.User.join_guests | def join_guests
#::Faalis::Group.find_by(role: 'guest')
if groups.empty?
guest_group = ::Faalis::Group.find_or_create_by(name: 'Guest',
role: 'guest')
self.groups << guest_group
end
end | ruby | def join_guests
#::Faalis::Group.find_by(role: 'guest')
if groups.empty?
guest_group = ::Faalis::Group.find_or_create_by(name: 'Guest',
role: 'guest')
self.groups << guest_group
end
end | [
"def",
"join_guests",
"if",
"groups",
".",
"empty?",
"guest_group",
"=",
"::",
"Faalis",
"::",
"Group",
".",
"find_or_create_by",
"(",
"name",
":",
"'Guest'",
",",
"role",
":",
"'guest'",
")",
"self",
".",
"groups",
"<<",
"guest_group",
"end",
"end"
] | It's totally obviuse. Join the guest group if no group provided | [
"It",
"s",
"totally",
"obviuse",
".",
"Join",
"the",
"guest",
"group",
"if",
"no",
"group",
"provided"
] | d12abdb8559dabbf6b2044e3ba437038527039b2 | https://github.com/Yellowen/Faalis/blob/d12abdb8559dabbf6b2044e3ba437038527039b2/app/models/faalis/user.rb#L67-L74 | train |
Yellowen/Faalis | lib/faalis/dashboard/dsl/base.rb | Faalis::Dashboard::DSL.Base.attributes | def attributes(*fields_name, **options, &block)
if options.include? :except
@fields = resolve_model_reflections.reject do |field|
options[:except].include? field.to_sym
end
elsif options.include? :append
@fields += options[:append]
else
# Check for valid field names
fields_name.each do |name|
unless @fields.include? name.to_s
raise ArgumentError, "can't find '#{name}' field for model '#{model}'."
end
end
# set new value for fields
@fields = fields_name.map(&:to_s) unless fields_name.empty?
end
@fields.concat(block.call.map(&:to_s)) if block_given?
end | ruby | def attributes(*fields_name, **options, &block)
if options.include? :except
@fields = resolve_model_reflections.reject do |field|
options[:except].include? field.to_sym
end
elsif options.include? :append
@fields += options[:append]
else
# Check for valid field names
fields_name.each do |name|
unless @fields.include? name.to_s
raise ArgumentError, "can't find '#{name}' field for model '#{model}'."
end
end
# set new value for fields
@fields = fields_name.map(&:to_s) unless fields_name.empty?
end
@fields.concat(block.call.map(&:to_s)) if block_given?
end | [
"def",
"attributes",
"(",
"*",
"fields_name",
",",
"**",
"options",
",",
"&",
"block",
")",
"if",
"options",
".",
"include?",
":except",
"@fields",
"=",
"resolve_model_reflections",
".",
"reject",
"do",
"|",
"field",
"|",
"options",
"[",
":except",
"]",
".",
"include?",
"field",
".",
"to_sym",
"end",
"elsif",
"options",
".",
"include?",
":append",
"@fields",
"+=",
"options",
"[",
":append",
"]",
"else",
"fields_name",
".",
"each",
"do",
"|",
"name",
"|",
"unless",
"@fields",
".",
"include?",
"name",
".",
"to_s",
"raise",
"ArgumentError",
",",
"\"can't find '#{name}' field for model '#{model}'.\"",
"end",
"end",
"@fields",
"=",
"fields_name",
".",
"map",
"(",
"&",
":to_s",
")",
"unless",
"fields_name",
".",
"empty?",
"end",
"@fields",
".",
"concat",
"(",
"block",
".",
"call",
".",
"map",
"(",
"&",
":to_s",
")",
")",
"if",
"block_given?",
"end"
] | Base class for all the DSL property classes to be
used as the yielded object inside each section DSL
scope.
For example the below code will yield an instance of
one of this class children.
in_index do
# This will yield an instance of this class child
end
The most important note in this class is that all the public
methods that their name starts with an underscore (_) not meant to
be used as DSL.
Allow user to specify an array of model attributes to be used
in respected section. For example attributes to show as header
columns in index section | [
"Base",
"class",
"for",
"all",
"the",
"DSL",
"property",
"classes",
"to",
"be",
"used",
"as",
"the",
"yielded",
"object",
"inside",
"each",
"section",
"DSL",
"scope",
"."
] | d12abdb8559dabbf6b2044e3ba437038527039b2 | https://github.com/Yellowen/Faalis/blob/d12abdb8559dabbf6b2044e3ba437038527039b2/lib/faalis/dashboard/dsl/base.rb#L32-L53 | train |
Yellowen/Faalis | lib/faalis/dashboard/dsl/base.rb | Faalis::Dashboard::DSL.Base.resolve_model_reflections | def resolve_model_reflections
# TODO: cach the result using and instance_var or something
reflections = model.reflections
columns = Set.new model.column_names
new_fields = Set.new
fields_to_remove = Set.new
reflections.each do |name, column|
has_many = ActiveRecord::Reflection::HasManyReflection
has_and_belongs_to_many = ActiveRecord::Reflection::HasAndBelongsToManyReflection
if !column.is_a?(has_many) && !column.is_a?(has_and_belongs_to_many)
new_fields << name.to_s
fields_to_remove << column.foreign_key.to_s
end
end
if model.respond_to? :attachment_definitions
# Paperclip is installed and model contains attachments
model.attachment_definitions.each do |name, _|
new_fields << name.to_s
["file_name", "content_type", "file_size", "updated_at"].each do |x|
fields_to_remove << "#{name}_#{x}"
end
end
end
columns.union(new_fields) - fields_to_remove
end | ruby | def resolve_model_reflections
# TODO: cach the result using and instance_var or something
reflections = model.reflections
columns = Set.new model.column_names
new_fields = Set.new
fields_to_remove = Set.new
reflections.each do |name, column|
has_many = ActiveRecord::Reflection::HasManyReflection
has_and_belongs_to_many = ActiveRecord::Reflection::HasAndBelongsToManyReflection
if !column.is_a?(has_many) && !column.is_a?(has_and_belongs_to_many)
new_fields << name.to_s
fields_to_remove << column.foreign_key.to_s
end
end
if model.respond_to? :attachment_definitions
# Paperclip is installed and model contains attachments
model.attachment_definitions.each do |name, _|
new_fields << name.to_s
["file_name", "content_type", "file_size", "updated_at"].each do |x|
fields_to_remove << "#{name}_#{x}"
end
end
end
columns.union(new_fields) - fields_to_remove
end | [
"def",
"resolve_model_reflections",
"reflections",
"=",
"model",
".",
"reflections",
"columns",
"=",
"Set",
".",
"new",
"model",
".",
"column_names",
"new_fields",
"=",
"Set",
".",
"new",
"fields_to_remove",
"=",
"Set",
".",
"new",
"reflections",
".",
"each",
"do",
"|",
"name",
",",
"column",
"|",
"has_many",
"=",
"ActiveRecord",
"::",
"Reflection",
"::",
"HasManyReflection",
"has_and_belongs_to_many",
"=",
"ActiveRecord",
"::",
"Reflection",
"::",
"HasAndBelongsToManyReflection",
"if",
"!",
"column",
".",
"is_a?",
"(",
"has_many",
")",
"&&",
"!",
"column",
".",
"is_a?",
"(",
"has_and_belongs_to_many",
")",
"new_fields",
"<<",
"name",
".",
"to_s",
"fields_to_remove",
"<<",
"column",
".",
"foreign_key",
".",
"to_s",
"end",
"end",
"if",
"model",
".",
"respond_to?",
":attachment_definitions",
"model",
".",
"attachment_definitions",
".",
"each",
"do",
"|",
"name",
",",
"_",
"|",
"new_fields",
"<<",
"name",
".",
"to_s",
"[",
"\"file_name\"",
",",
"\"content_type\"",
",",
"\"file_size\"",
",",
"\"updated_at\"",
"]",
".",
"each",
"do",
"|",
"x",
"|",
"fields_to_remove",
"<<",
"\"#{name}_#{x}\"",
"end",
"end",
"end",
"columns",
".",
"union",
"(",
"new_fields",
")",
"-",
"fields_to_remove",
"end"
] | Replace foreign key names with their reflection names
and create an array of model fields | [
"Replace",
"foreign",
"key",
"names",
"with",
"their",
"reflection",
"names",
"and",
"create",
"an",
"array",
"of",
"model",
"fields"
] | d12abdb8559dabbf6b2044e3ba437038527039b2 | https://github.com/Yellowen/Faalis/blob/d12abdb8559dabbf6b2044e3ba437038527039b2/lib/faalis/dashboard/dsl/base.rb#L103-L131 | train |
kjvarga/ajax | lib/ajax/application.rb | Ajax.Application.rails? | def rails?(*args)
version, comparator = args.pop, (args.pop || :==)
result =
if version.nil?
defined?(::Rails)
elsif defined?(::Rails)
if ::Rails.respond_to?(:version)
rails_version = Rails.version.to_f
rails_version = rails_version.floor if version.is_a?(Integer)
rails_version.send(comparator, version.to_f)
else
version.to_f <= 2.0
end
else
false
end
!!result
end | ruby | def rails?(*args)
version, comparator = args.pop, (args.pop || :==)
result =
if version.nil?
defined?(::Rails)
elsif defined?(::Rails)
if ::Rails.respond_to?(:version)
rails_version = Rails.version.to_f
rails_version = rails_version.floor if version.is_a?(Integer)
rails_version.send(comparator, version.to_f)
else
version.to_f <= 2.0
end
else
false
end
!!result
end | [
"def",
"rails?",
"(",
"*",
"args",
")",
"version",
",",
"comparator",
"=",
"args",
".",
"pop",
",",
"(",
"args",
".",
"pop",
"||",
":==",
")",
"result",
"=",
"if",
"version",
".",
"nil?",
"defined?",
"(",
"::",
"Rails",
")",
"elsif",
"defined?",
"(",
"::",
"Rails",
")",
"if",
"::",
"Rails",
".",
"respond_to?",
"(",
":version",
")",
"rails_version",
"=",
"Rails",
".",
"version",
".",
"to_f",
"rails_version",
"=",
"rails_version",
".",
"floor",
"if",
"version",
".",
"is_a?",
"(",
"Integer",
")",
"rails_version",
".",
"send",
"(",
"comparator",
",",
"version",
".",
"to_f",
")",
"else",
"version",
".",
"to_f",
"<=",
"2.0",
"end",
"else",
"false",
"end",
"!",
"!",
"result",
"end"
] | Return a boolean indicating whether the Rails constant is defined.
It cannot identify Rails < 2.1
Example:
rails?(3) => true if Rails major version is 3
rails?(3.0) => true if Rails major.minor version is 3.0
rails?(:>=, 3) => true if Rails major version is >= 3
rails?(:>=, 3.1) => true if Rails major.minor version is >= 3.1 | [
"Return",
"a",
"boolean",
"indicating",
"whether",
"the",
"Rails",
"constant",
"is",
"defined",
".",
"It",
"cannot",
"identify",
"Rails",
"<",
"2",
".",
"1"
] | e60acbc51855cd85b4907d509ea41fe0965ce72e | https://github.com/kjvarga/ajax/blob/e60acbc51855cd85b4907d509ea41fe0965ce72e/lib/ajax/application.rb#L15-L32 | train |
kjvarga/ajax | lib/ajax/application.rb | Ajax.Application.init | def init
return unless rails?
if rails?(:>=, 3)
require 'ajax/railtie'
else
require 'ajax/action_controller'
require 'ajax/action_view'
Ajax.logger = ::Rails.logger
# Customize rendering. Include custom headers and don't render the layout for AJAX.
::ActionController::Base.send(:include, Ajax::ActionController)
# Insert the Rack::Ajax middleware to rewrite and handle requests
::ActionController::Dispatcher.middleware.insert_before(Rack::Head, Rack::Ajax)
# Add custom attributes to outgoing links
::ActionView::Base.send(:include, Ajax::ActionView)
end
end | ruby | def init
return unless rails?
if rails?(:>=, 3)
require 'ajax/railtie'
else
require 'ajax/action_controller'
require 'ajax/action_view'
Ajax.logger = ::Rails.logger
# Customize rendering. Include custom headers and don't render the layout for AJAX.
::ActionController::Base.send(:include, Ajax::ActionController)
# Insert the Rack::Ajax middleware to rewrite and handle requests
::ActionController::Dispatcher.middleware.insert_before(Rack::Head, Rack::Ajax)
# Add custom attributes to outgoing links
::ActionView::Base.send(:include, Ajax::ActionView)
end
end | [
"def",
"init",
"return",
"unless",
"rails?",
"if",
"rails?",
"(",
":>=",
",",
"3",
")",
"require",
"'ajax/railtie'",
"else",
"require",
"'ajax/action_controller'",
"require",
"'ajax/action_view'",
"Ajax",
".",
"logger",
"=",
"::",
"Rails",
".",
"logger",
"::",
"ActionController",
"::",
"Base",
".",
"send",
"(",
":include",
",",
"Ajax",
"::",
"ActionController",
")",
"::",
"ActionController",
"::",
"Dispatcher",
".",
"middleware",
".",
"insert_before",
"(",
"Rack",
"::",
"Head",
",",
"Rack",
"::",
"Ajax",
")",
"::",
"ActionView",
"::",
"Base",
".",
"send",
"(",
":include",
",",
"Ajax",
"::",
"ActionView",
")",
"end",
"end"
] | Include framework hooks for Rails
This method is called by <tt>init.rb</tt>, which is run by Rails on startup.
Customize rendering. Include custom headers and don't render the layout for AJAX.
Insert the Rack::Ajax middleware to rewrite and handle requests.
Add custom attributes to outgoing links.
Hooks for Rails 3 are installed using Railties. | [
"Include",
"framework",
"hooks",
"for",
"Rails"
] | e60acbc51855cd85b4907d509ea41fe0965ce72e | https://github.com/kjvarga/ajax/blob/e60acbc51855cd85b4907d509ea41fe0965ce72e/lib/ajax/application.rb#L47-L66 | train |
opulent/opulent | lib/opulent/compiler/eval.rb | Opulent.Compiler.evaluate | def evaluate(node, indent)
# Check if this is a substructure of a control block and remove the last
# end evaluation if it is
if node[@value] =~ Settings::END_REMOVAL
@template.pop if @template[-1] == [:eval, 'end']
end
# Check for explicit end node
if node[@value] =~ Settings::END_EXPLICIT
Logger.error :compile, @template, :explicit_end, node
end
# Evaluate the current expression
buffer_eval node[@value]
# If the node has children, evaluate each one of them
node[@children].each do |child|
root child, indent + @settings[:indent]
end if node[@children]
# Check if the node is actually a block expression
buffer_eval 'end' if node[@value] =~ Settings::END_INSERTION
end | ruby | def evaluate(node, indent)
# Check if this is a substructure of a control block and remove the last
# end evaluation if it is
if node[@value] =~ Settings::END_REMOVAL
@template.pop if @template[-1] == [:eval, 'end']
end
# Check for explicit end node
if node[@value] =~ Settings::END_EXPLICIT
Logger.error :compile, @template, :explicit_end, node
end
# Evaluate the current expression
buffer_eval node[@value]
# If the node has children, evaluate each one of them
node[@children].each do |child|
root child, indent + @settings[:indent]
end if node[@children]
# Check if the node is actually a block expression
buffer_eval 'end' if node[@value] =~ Settings::END_INSERTION
end | [
"def",
"evaluate",
"(",
"node",
",",
"indent",
")",
"if",
"node",
"[",
"@value",
"]",
"=~",
"Settings",
"::",
"END_REMOVAL",
"@template",
".",
"pop",
"if",
"@template",
"[",
"-",
"1",
"]",
"==",
"[",
":eval",
",",
"'end'",
"]",
"end",
"if",
"node",
"[",
"@value",
"]",
"=~",
"Settings",
"::",
"END_EXPLICIT",
"Logger",
".",
"error",
":compile",
",",
"@template",
",",
":explicit_end",
",",
"node",
"end",
"buffer_eval",
"node",
"[",
"@value",
"]",
"node",
"[",
"@children",
"]",
".",
"each",
"do",
"|",
"child",
"|",
"root",
"child",
",",
"indent",
"+",
"@settings",
"[",
":indent",
"]",
"end",
"if",
"node",
"[",
"@children",
"]",
"buffer_eval",
"'end'",
"if",
"node",
"[",
"@value",
"]",
"=~",
"Settings",
"::",
"END_INSERTION",
"end"
] | Evaluate the embedded ruby code using the current context
@param node [Array] Node code generation data
@param indent [Fixnum] Size of the indentation to be added | [
"Evaluate",
"the",
"embedded",
"ruby",
"code",
"using",
"the",
"current",
"context"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/compiler/eval.rb#L10-L32 | train |
Yellowen/Faalis | lib/faalis/routes.rb | Faalis.RouteHelpers.localized_scope | def localized_scope
langs = ::I18n.available_locales.join('|')
scope '(:locale)', locale: Regexp.new(langs) do
yield
end
end | ruby | def localized_scope
langs = ::I18n.available_locales.join('|')
scope '(:locale)', locale: Regexp.new(langs) do
yield
end
end | [
"def",
"localized_scope",
"langs",
"=",
"::",
"I18n",
".",
"available_locales",
".",
"join",
"(",
"'|'",
")",
"scope",
"'(:locale)'",
",",
"locale",
":",
"Regexp",
".",
"new",
"(",
"langs",
")",
"do",
"yield",
"end",
"end"
] | Allow localized scope | [
"Allow",
"localized",
"scope"
] | d12abdb8559dabbf6b2044e3ba437038527039b2 | https://github.com/Yellowen/Faalis/blob/d12abdb8559dabbf6b2044e3ba437038527039b2/lib/faalis/routes.rb#L12-L17 | train |
Yellowen/Faalis | lib/faalis/routes.rb | Faalis.RouteHelpers.api_routes | def api_routes(version: :v1)
# TODO: Add a dynamic solution for formats
namespace :api, defaults: { format: :json } do
namespace version do
# Call user given block to define user routes
# inside this namespace
yield if block_given?
end
end
scope 'module'.to_sym => 'faalis' do
#dashboard = Faalis::Engine.dashboard_namespace
#get "#{dashboard}/auth/groups/new", to: "#{dashboard}/groups#new"
get 'auth/profile/edit', to: "profile#edit"
post 'auth/profile/edit', to: "profile#update"
end
# TODO: Add a dynamic solution for formats
namespace :api, defaults: { format: :json } do
namespace version do
get 'permissions', to: 'permissions#index'
get 'permissions/user', to: 'permissions#user_permissions'
resources :groups, except: [:new]
resources :users, except: [:new]
resource :profile, except: [:new, :destroy]
get 'logs', to: 'logs#index'
end
end
end | ruby | def api_routes(version: :v1)
# TODO: Add a dynamic solution for formats
namespace :api, defaults: { format: :json } do
namespace version do
# Call user given block to define user routes
# inside this namespace
yield if block_given?
end
end
scope 'module'.to_sym => 'faalis' do
#dashboard = Faalis::Engine.dashboard_namespace
#get "#{dashboard}/auth/groups/new", to: "#{dashboard}/groups#new"
get 'auth/profile/edit', to: "profile#edit"
post 'auth/profile/edit', to: "profile#update"
end
# TODO: Add a dynamic solution for formats
namespace :api, defaults: { format: :json } do
namespace version do
get 'permissions', to: 'permissions#index'
get 'permissions/user', to: 'permissions#user_permissions'
resources :groups, except: [:new]
resources :users, except: [:new]
resource :profile, except: [:new, :destroy]
get 'logs', to: 'logs#index'
end
end
end | [
"def",
"api_routes",
"(",
"version",
":",
":v1",
")",
"namespace",
":api",
",",
"defaults",
":",
"{",
"format",
":",
":json",
"}",
"do",
"namespace",
"version",
"do",
"yield",
"if",
"block_given?",
"end",
"end",
"scope",
"'module'",
".",
"to_sym",
"=>",
"'faalis'",
"do",
"get",
"'auth/profile/edit'",
",",
"to",
":",
"\"profile#edit\"",
"post",
"'auth/profile/edit'",
",",
"to",
":",
"\"profile#update\"",
"end",
"namespace",
":api",
",",
"defaults",
":",
"{",
"format",
":",
":json",
"}",
"do",
"namespace",
"version",
"do",
"get",
"'permissions'",
",",
"to",
":",
"'permissions#index'",
"get",
"'permissions/user'",
",",
"to",
":",
"'permissions#user_permissions'",
"resources",
":groups",
",",
"except",
":",
"[",
":new",
"]",
"resources",
":users",
",",
"except",
":",
"[",
":new",
"]",
"resource",
":profile",
",",
"except",
":",
"[",
":new",
",",
":destroy",
"]",
"get",
"'logs'",
",",
"to",
":",
"'logs#index'",
"end",
"end",
"end"
] | This method allow user to define his routes in api
namespace | [
"This",
"method",
"allow",
"user",
"to",
"define",
"his",
"routes",
"in",
"api",
"namespace"
] | d12abdb8559dabbf6b2044e3ba437038527039b2 | https://github.com/Yellowen/Faalis/blob/d12abdb8559dabbf6b2044e3ba437038527039b2/lib/faalis/routes.rb#L21-L50 | train |
beatrichartz/configurations | lib/configurations/configuration.rb | Configurations.Configuration.to_h | def to_h
@data.reduce({}) do |h, (k, v)|
h[k] = v.is_a?(__class__) ? v.to_h : v
h
end
end | ruby | def to_h
@data.reduce({}) do |h, (k, v)|
h[k] = v.is_a?(__class__) ? v.to_h : v
h
end
end | [
"def",
"to_h",
"@data",
".",
"reduce",
"(",
"{",
"}",
")",
"do",
"|",
"h",
",",
"(",
"k",
",",
"v",
")",
"|",
"h",
"[",
"k",
"]",
"=",
"v",
".",
"is_a?",
"(",
"__class__",
")",
"?",
"v",
".",
"to_h",
":",
"v",
"h",
"end",
"end"
] | A convenience accessor to get a hash representation of the
current state of the configuration
@return [Hash] the configuration in hash form | [
"A",
"convenience",
"accessor",
"to",
"get",
"a",
"hash",
"representation",
"of",
"the",
"current",
"state",
"of",
"the",
"configuration"
] | bd8ef480ca831e29b821ffc9ebeaed4ef46a9db2 | https://github.com/beatrichartz/configurations/blob/bd8ef480ca831e29b821ffc9ebeaed4ef46a9db2/lib/configurations/configuration.rb#L59-L65 | train |
beatrichartz/configurations | lib/configurations/configuration.rb | Configurations.Configuration.from_h | def from_h(h)
@key_ambiguity_validator.validate!(h)
h.each do |property, value|
p = property.to_sym
if value.is_a?(::Hash) && __nested?(p)
@data[p].from_h(value)
elsif __configurable?(p)
__assign!(p, value)
end
end
self
end | ruby | def from_h(h)
@key_ambiguity_validator.validate!(h)
h.each do |property, value|
p = property.to_sym
if value.is_a?(::Hash) && __nested?(p)
@data[p].from_h(value)
elsif __configurable?(p)
__assign!(p, value)
end
end
self
end | [
"def",
"from_h",
"(",
"h",
")",
"@key_ambiguity_validator",
".",
"validate!",
"(",
"h",
")",
"h",
".",
"each",
"do",
"|",
"property",
",",
"value",
"|",
"p",
"=",
"property",
".",
"to_sym",
"if",
"value",
".",
"is_a?",
"(",
"::",
"Hash",
")",
"&&",
"__nested?",
"(",
"p",
")",
"@data",
"[",
"p",
"]",
".",
"from_h",
"(",
"value",
")",
"elsif",
"__configurable?",
"(",
"p",
")",
"__assign!",
"(",
"p",
",",
"value",
")",
"end",
"end",
"self",
"end"
] | A convenience accessor to instantiate a configuration from a hash
@param [Hash] h the hash to read into the configuration
@return [Configuration] the configuration with values assigned
@raise [ConfigurationError] if the given hash ambiguous values
- string and symbol keys with the same string value pointing to
different values | [
"A",
"convenience",
"accessor",
"to",
"instantiate",
"a",
"configuration",
"from",
"a",
"hash"
] | bd8ef480ca831e29b821ffc9ebeaed4ef46a9db2 | https://github.com/beatrichartz/configurations/blob/bd8ef480ca831e29b821ffc9ebeaed4ef46a9db2/lib/configurations/configuration.rb#L74-L87 | train |
opulent/opulent | lib/opulent/compiler/control.rb | Opulent.Compiler.if_node | def if_node(node, indent)
# Check if we have any condition met, or an else branch
node[@value].each_with_index do |value, index|
# If we have a branch that meets the condition, generate code for the
# children related to that specific branch
case value
when node[@value].first then buffer_eval "if #{value}"
when node[@value].last then buffer_eval "else"
else buffer_eval "elsif #{value}"
end
# Evaluate child nodes
node[@children][index].each do |child|
root child, indent
end
end
# End
buffer_eval "end"
end | ruby | def if_node(node, indent)
# Check if we have any condition met, or an else branch
node[@value].each_with_index do |value, index|
# If we have a branch that meets the condition, generate code for the
# children related to that specific branch
case value
when node[@value].first then buffer_eval "if #{value}"
when node[@value].last then buffer_eval "else"
else buffer_eval "elsif #{value}"
end
# Evaluate child nodes
node[@children][index].each do |child|
root child, indent
end
end
# End
buffer_eval "end"
end | [
"def",
"if_node",
"(",
"node",
",",
"indent",
")",
"node",
"[",
"@value",
"]",
".",
"each_with_index",
"do",
"|",
"value",
",",
"index",
"|",
"case",
"value",
"when",
"node",
"[",
"@value",
"]",
".",
"first",
"then",
"buffer_eval",
"\"if #{value}\"",
"when",
"node",
"[",
"@value",
"]",
".",
"last",
"then",
"buffer_eval",
"\"else\"",
"else",
"buffer_eval",
"\"elsif #{value}\"",
"end",
"node",
"[",
"@children",
"]",
"[",
"index",
"]",
".",
"each",
"do",
"|",
"child",
"|",
"root",
"child",
",",
"indent",
"end",
"end",
"buffer_eval",
"\"end\"",
"end"
] | Generate the code for a if-elsif-else control structure
@param node [Array] Node code generation data
@param indent [Fixnum] Size of the indentation to be added | [
"Generate",
"the",
"code",
"for",
"a",
"if",
"-",
"elsif",
"-",
"else",
"control",
"structure"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/compiler/control.rb#L10-L29 | train |
opulent/opulent | lib/opulent/compiler/control.rb | Opulent.Compiler.unless_node | def unless_node(node, indent)
# Check if we have any condition met, or an else branch
node[@value].each_with_index do |value, index|
# If we have a branch that meets the condition, generate code for the
# children related to that specific branch
case value
when node[@value].first then buffer_eval "unless #{value}"
else buffer_eval "else"
end
# Evaluate child nodes
node[@children][index].each do |child|
root child, indent
end
end
# End
buffer_eval "end"
end | ruby | def unless_node(node, indent)
# Check if we have any condition met, or an else branch
node[@value].each_with_index do |value, index|
# If we have a branch that meets the condition, generate code for the
# children related to that specific branch
case value
when node[@value].first then buffer_eval "unless #{value}"
else buffer_eval "else"
end
# Evaluate child nodes
node[@children][index].each do |child|
root child, indent
end
end
# End
buffer_eval "end"
end | [
"def",
"unless_node",
"(",
"node",
",",
"indent",
")",
"node",
"[",
"@value",
"]",
".",
"each_with_index",
"do",
"|",
"value",
",",
"index",
"|",
"case",
"value",
"when",
"node",
"[",
"@value",
"]",
".",
"first",
"then",
"buffer_eval",
"\"unless #{value}\"",
"else",
"buffer_eval",
"\"else\"",
"end",
"node",
"[",
"@children",
"]",
"[",
"index",
"]",
".",
"each",
"do",
"|",
"child",
"|",
"root",
"child",
",",
"indent",
"end",
"end",
"buffer_eval",
"\"end\"",
"end"
] | Generate the code for a unless-else control structure
@param node [Array] Node code generation data
@param indent [Fixnum] Size of the indentation to be added | [
"Generate",
"the",
"code",
"for",
"a",
"unless",
"-",
"else",
"control",
"structure"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/compiler/control.rb#L36-L54 | train |
opulent/opulent | lib/opulent/compiler/control.rb | Opulent.Compiler.case_node | def case_node(node, indent)
# Evaluate the switching condition
buffer_eval "case #{node[@options][:condition]}"
# Check if we have any condition met, or an else branch
node[@value].each_with_index do |value, index|
# If we have a branch that meets the condition, generate code for the
# children related to that specific branch
case value
when node[@value].last then buffer_eval 'else'
else buffer_eval "when #{value}"
end
# Evaluate child nodes
node[@children][index].each do |child|
root child, indent
end
end
# End
buffer_eval 'end'
end | ruby | def case_node(node, indent)
# Evaluate the switching condition
buffer_eval "case #{node[@options][:condition]}"
# Check if we have any condition met, or an else branch
node[@value].each_with_index do |value, index|
# If we have a branch that meets the condition, generate code for the
# children related to that specific branch
case value
when node[@value].last then buffer_eval 'else'
else buffer_eval "when #{value}"
end
# Evaluate child nodes
node[@children][index].each do |child|
root child, indent
end
end
# End
buffer_eval 'end'
end | [
"def",
"case_node",
"(",
"node",
",",
"indent",
")",
"buffer_eval",
"\"case #{node[@options][:condition]}\"",
"node",
"[",
"@value",
"]",
".",
"each_with_index",
"do",
"|",
"value",
",",
"index",
"|",
"case",
"value",
"when",
"node",
"[",
"@value",
"]",
".",
"last",
"then",
"buffer_eval",
"'else'",
"else",
"buffer_eval",
"\"when #{value}\"",
"end",
"node",
"[",
"@children",
"]",
"[",
"index",
"]",
".",
"each",
"do",
"|",
"child",
"|",
"root",
"child",
",",
"indent",
"end",
"end",
"buffer_eval",
"'end'",
"end"
] | Generate the code for a case-when-else control structure
@param node [Array] Node code generation data
@param indent [Fixnum] Size of the indentation to be added | [
"Generate",
"the",
"code",
"for",
"a",
"case",
"-",
"when",
"-",
"else",
"control",
"structure"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/compiler/control.rb#L61-L82 | train |
mdub/representative | lib/representative/nokogiri.rb | Representative.Nokogiri.comment | def comment(text)
comment_node = ::Nokogiri::XML::Comment.new(doc, " #{text} ")
current_element.add_child(comment_node)
end | ruby | def comment(text)
comment_node = ::Nokogiri::XML::Comment.new(doc, " #{text} ")
current_element.add_child(comment_node)
end | [
"def",
"comment",
"(",
"text",
")",
"comment_node",
"=",
"::",
"Nokogiri",
"::",
"XML",
"::",
"Comment",
".",
"new",
"(",
"doc",
",",
"\" #{text} \"",
")",
"current_element",
".",
"add_child",
"(",
"comment_node",
")",
"end"
] | Generate a comment | [
"Generate",
"a",
"comment"
] | c60214e79d51581a1744ae2891094468416b88f9 | https://github.com/mdub/representative/blob/c60214e79d51581a1744ae2891094468416b88f9/lib/representative/nokogiri.rb#L33-L36 | train |
opulent/opulent | lib/opulent/parser/node.rb | Opulent.Parser.node | def node(parent, indent = nil)
return unless (name = lookahead(:node_lookahead) ||
lookahead(:shorthand_lookahead))
# Skip node if it's a reserved keyword
return nil if KEYWORDS.include? name[0].to_sym
# Accept either explicit node_name or implicit :div node_name
# with shorthand attributes
if (node_name = accept :node)
node_name = node_name.to_sym
shorthand = shorthand_attributes
elsif (shorthand = shorthand_attributes)
node_name = :div
end
# Node creation options
options = {}
# Get leading whitespace
options[:recursive] = accept(:recursive)
# Get leading whitespace
options[:leading_whitespace] = accept_stripped(:leading_whitespace)
# Get trailing whitespace
options[:trailing_whitespace] = accept_stripped(:trailing_whitespace)
# Get wrapped node attributes
atts = attributes(shorthand) || {}
# Inherit attributes from definition
options[:extension] = extend_attributes
# Get unwrapped node attributes
options[:attributes] = attributes_assignments atts, false
# Create node
current_node = [:node, node_name, options, [], indent]
# Check for self enclosing tags and definitions
def_check = [email protected]?(node_name) &&
Settings::SELF_ENCLOSING.include?(node_name)
# Check if the node is explicitly self enclosing
if (close = accept_stripped :self_enclosing) || def_check
current_node[@options][:self_enclosing] = true
unless close.nil? || close.strip.empty?
undo close
Logger.error :parse, @code, @i, @j, :self_enclosing
end
end
# Check whether we have explicit inline elements and add them
# with increased base indentation
if accept :inline_child
# Inline node element
Logger.error :parse,
@code,
@i,
@j,
:inline_child unless node current_node, indent
elsif comment current_node, indent
# Accept same line comments
else
# Accept inline text element
text current_node, indent, false
end
# Add the current node to the root
root current_node, indent
# Add the parsed node to the parent
parent[@children] << current_node
end | ruby | def node(parent, indent = nil)
return unless (name = lookahead(:node_lookahead) ||
lookahead(:shorthand_lookahead))
# Skip node if it's a reserved keyword
return nil if KEYWORDS.include? name[0].to_sym
# Accept either explicit node_name or implicit :div node_name
# with shorthand attributes
if (node_name = accept :node)
node_name = node_name.to_sym
shorthand = shorthand_attributes
elsif (shorthand = shorthand_attributes)
node_name = :div
end
# Node creation options
options = {}
# Get leading whitespace
options[:recursive] = accept(:recursive)
# Get leading whitespace
options[:leading_whitespace] = accept_stripped(:leading_whitespace)
# Get trailing whitespace
options[:trailing_whitespace] = accept_stripped(:trailing_whitespace)
# Get wrapped node attributes
atts = attributes(shorthand) || {}
# Inherit attributes from definition
options[:extension] = extend_attributes
# Get unwrapped node attributes
options[:attributes] = attributes_assignments atts, false
# Create node
current_node = [:node, node_name, options, [], indent]
# Check for self enclosing tags and definitions
def_check = [email protected]?(node_name) &&
Settings::SELF_ENCLOSING.include?(node_name)
# Check if the node is explicitly self enclosing
if (close = accept_stripped :self_enclosing) || def_check
current_node[@options][:self_enclosing] = true
unless close.nil? || close.strip.empty?
undo close
Logger.error :parse, @code, @i, @j, :self_enclosing
end
end
# Check whether we have explicit inline elements and add them
# with increased base indentation
if accept :inline_child
# Inline node element
Logger.error :parse,
@code,
@i,
@j,
:inline_child unless node current_node, indent
elsif comment current_node, indent
# Accept same line comments
else
# Accept inline text element
text current_node, indent, false
end
# Add the current node to the root
root current_node, indent
# Add the parsed node to the parent
parent[@children] << current_node
end | [
"def",
"node",
"(",
"parent",
",",
"indent",
"=",
"nil",
")",
"return",
"unless",
"(",
"name",
"=",
"lookahead",
"(",
":node_lookahead",
")",
"||",
"lookahead",
"(",
":shorthand_lookahead",
")",
")",
"return",
"nil",
"if",
"KEYWORDS",
".",
"include?",
"name",
"[",
"0",
"]",
".",
"to_sym",
"if",
"(",
"node_name",
"=",
"accept",
":node",
")",
"node_name",
"=",
"node_name",
".",
"to_sym",
"shorthand",
"=",
"shorthand_attributes",
"elsif",
"(",
"shorthand",
"=",
"shorthand_attributes",
")",
"node_name",
"=",
":div",
"end",
"options",
"=",
"{",
"}",
"options",
"[",
":recursive",
"]",
"=",
"accept",
"(",
":recursive",
")",
"options",
"[",
":leading_whitespace",
"]",
"=",
"accept_stripped",
"(",
":leading_whitespace",
")",
"options",
"[",
":trailing_whitespace",
"]",
"=",
"accept_stripped",
"(",
":trailing_whitespace",
")",
"atts",
"=",
"attributes",
"(",
"shorthand",
")",
"||",
"{",
"}",
"options",
"[",
":extension",
"]",
"=",
"extend_attributes",
"options",
"[",
":attributes",
"]",
"=",
"attributes_assignments",
"atts",
",",
"false",
"current_node",
"=",
"[",
":node",
",",
"node_name",
",",
"options",
",",
"[",
"]",
",",
"indent",
"]",
"def_check",
"=",
"!",
"@definitions",
".",
"keys",
".",
"include?",
"(",
"node_name",
")",
"&&",
"Settings",
"::",
"SELF_ENCLOSING",
".",
"include?",
"(",
"node_name",
")",
"if",
"(",
"close",
"=",
"accept_stripped",
":self_enclosing",
")",
"||",
"def_check",
"current_node",
"[",
"@options",
"]",
"[",
":self_enclosing",
"]",
"=",
"true",
"unless",
"close",
".",
"nil?",
"||",
"close",
".",
"strip",
".",
"empty?",
"undo",
"close",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":self_enclosing",
"end",
"end",
"if",
"accept",
":inline_child",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":inline_child",
"unless",
"node",
"current_node",
",",
"indent",
"elsif",
"comment",
"current_node",
",",
"indent",
"else",
"text",
"current_node",
",",
"indent",
",",
"false",
"end",
"root",
"current_node",
",",
"indent",
"parent",
"[",
"@children",
"]",
"<<",
"current_node",
"end"
] | Check if we match an node node with its attributes and possibly
inline text
node [ attributes ] Inline text
@param parent [Node] Parent node to which we append the node | [
"Check",
"if",
"we",
"match",
"an",
"node",
"node",
"with",
"its",
"attributes",
"and",
"possibly",
"inline",
"text"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/node.rb#L12-L87 | train |
opulent/opulent | lib/opulent/parser/node.rb | Opulent.Parser.shorthand_attributes | def shorthand_attributes(atts = {})
while (key = accept :shorthand)
key = Settings::SHORTHAND[key.to_sym]
# Check whether the value is escaped or unescaped
escaped = accept(:unescaped_value) ? false : true
# Get the attribute value and process it
if (value = accept(:shorthand_node))
value = [:expression, value.inspect, { escaped: escaped }]
elsif (value = accept(:exp_string))
value = [:expression, value, { escaped: escaped }]
elsif (value = paranthesis)
value = [:expression, value, { escaped: escaped }]
else
Logger.error :parse, @code, @i, @j, :shorthand
end
# IDs are unique, the rest of the attributes turn into arrays in
# order to allow multiple values or identifiers
add_attribute(atts, key, value)
end
atts
end | ruby | def shorthand_attributes(atts = {})
while (key = accept :shorthand)
key = Settings::SHORTHAND[key.to_sym]
# Check whether the value is escaped or unescaped
escaped = accept(:unescaped_value) ? false : true
# Get the attribute value and process it
if (value = accept(:shorthand_node))
value = [:expression, value.inspect, { escaped: escaped }]
elsif (value = accept(:exp_string))
value = [:expression, value, { escaped: escaped }]
elsif (value = paranthesis)
value = [:expression, value, { escaped: escaped }]
else
Logger.error :parse, @code, @i, @j, :shorthand
end
# IDs are unique, the rest of the attributes turn into arrays in
# order to allow multiple values or identifiers
add_attribute(atts, key, value)
end
atts
end | [
"def",
"shorthand_attributes",
"(",
"atts",
"=",
"{",
"}",
")",
"while",
"(",
"key",
"=",
"accept",
":shorthand",
")",
"key",
"=",
"Settings",
"::",
"SHORTHAND",
"[",
"key",
".",
"to_sym",
"]",
"escaped",
"=",
"accept",
"(",
":unescaped_value",
")",
"?",
"false",
":",
"true",
"if",
"(",
"value",
"=",
"accept",
"(",
":shorthand_node",
")",
")",
"value",
"=",
"[",
":expression",
",",
"value",
".",
"inspect",
",",
"{",
"escaped",
":",
"escaped",
"}",
"]",
"elsif",
"(",
"value",
"=",
"accept",
"(",
":exp_string",
")",
")",
"value",
"=",
"[",
":expression",
",",
"value",
",",
"{",
"escaped",
":",
"escaped",
"}",
"]",
"elsif",
"(",
"value",
"=",
"paranthesis",
")",
"value",
"=",
"[",
":expression",
",",
"value",
",",
"{",
"escaped",
":",
"escaped",
"}",
"]",
"else",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":shorthand",
"end",
"add_attribute",
"(",
"atts",
",",
"key",
",",
"value",
")",
"end",
"atts",
"end"
] | Accept node shorthand attributes. Each shorthand attribute is directly
mapped to an attribute key
@param atts [Hash] Node attributes | [
"Accept",
"node",
"shorthand",
"attributes",
".",
"Each",
"shorthand",
"attribute",
"is",
"directly",
"mapped",
"to",
"an",
"attribute",
"key"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/node.rb#L164-L188 | train |
opulent/opulent | lib/opulent/parser/node.rb | Opulent.Parser.attributes | def attributes(atts = {}, for_definition = false)
wrapped_attributes atts, for_definition
attributes_assignments atts, false, for_definition
atts
end | ruby | def attributes(atts = {}, for_definition = false)
wrapped_attributes atts, for_definition
attributes_assignments atts, false, for_definition
atts
end | [
"def",
"attributes",
"(",
"atts",
"=",
"{",
"}",
",",
"for_definition",
"=",
"false",
")",
"wrapped_attributes",
"atts",
",",
"for_definition",
"attributes_assignments",
"atts",
",",
"false",
",",
"for_definition",
"atts",
"end"
] | Get element attributes
@param atts [Hash] Accumulator for node attributes
@param for_definition [Boolean] Set default value in wrapped to nil | [
"Get",
"element",
"attributes"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/node.rb#L195-L199 | train |
opulent/opulent | lib/opulent/parser/node.rb | Opulent.Parser.wrapped_attributes | def wrapped_attributes(list = {}, for_definition = false)
return unless (bracket = accept :brackets)
accept_newline
attributes_assignments list, true, for_definition
accept_newline
accept_stripped bracket.to_sym, :*
list
end | ruby | def wrapped_attributes(list = {}, for_definition = false)
return unless (bracket = accept :brackets)
accept_newline
attributes_assignments list, true, for_definition
accept_newline
accept_stripped bracket.to_sym, :*
list
end | [
"def",
"wrapped_attributes",
"(",
"list",
"=",
"{",
"}",
",",
"for_definition",
"=",
"false",
")",
"return",
"unless",
"(",
"bracket",
"=",
"accept",
":brackets",
")",
"accept_newline",
"attributes_assignments",
"list",
",",
"true",
",",
"for_definition",
"accept_newline",
"accept_stripped",
"bracket",
".",
"to_sym",
",",
":*",
"list",
"end"
] | Check if we match node attributes
[ assignments ]
@param as_parameters [Boolean] Accept or reject identifier nodes | [
"Check",
"if",
"we",
"match",
"node",
"attributes"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/node.rb#L207-L217 | train |
opulent/opulent | lib/opulent/parser/node.rb | Opulent.Parser.attributes_assignments | def attributes_assignments(list, wrapped = true, for_definition = false)
if wrapped && lookahead(:exp_identifier_stripped_lookahead).nil? ||
!wrapped && lookahead(:assignment_lookahead).nil?
return list
end
return unless (argument = accept_stripped :node)
argument = argument.to_sym
if accept_stripped :assignment
# Check if we have an attribute escape or not
escaped = if accept :assignment_unescaped
false
else
true
end
# Get the argument value if we have an assignment
if (value = expression(false, wrapped))
value[@options][:escaped] = escaped
# IDs are unique, the rest of the attributes turn into arrays in
# order to allow multiple values or identifiers
add_attribute(list, argument, value)
else
Logger.error :parse, @code, @i, @j, :assignments_colon
end
else
unless list[argument]
default_value = for_definition ? 'nil' : 'true'
list[argument] = [:expression, default_value, { escaped: false }]
end
end
# If our attributes are wrapped, we allow method calls without
# paranthesis, ruby style, therefore we need a terminator to signify
# the expression end. If they are not wrapped (inline), we require
# paranthesis and allow inline calls
if wrapped
# Accept optional comma between attributes
accept_stripped :assignment_terminator
# Lookahead for attributes on the current line and the next one
if lookahead(:exp_identifier_stripped_lookahead)
attributes_assignments list, wrapped, for_definition
elsif lookahead_next_line(:exp_identifier_stripped_lookahead)
accept_newline
attributes_assignments list, wrapped, for_definition
end
elsif !wrapped && lookahead(:assignment_lookahead)
attributes_assignments list, wrapped, for_definition
end
list
end | ruby | def attributes_assignments(list, wrapped = true, for_definition = false)
if wrapped && lookahead(:exp_identifier_stripped_lookahead).nil? ||
!wrapped && lookahead(:assignment_lookahead).nil?
return list
end
return unless (argument = accept_stripped :node)
argument = argument.to_sym
if accept_stripped :assignment
# Check if we have an attribute escape or not
escaped = if accept :assignment_unescaped
false
else
true
end
# Get the argument value if we have an assignment
if (value = expression(false, wrapped))
value[@options][:escaped] = escaped
# IDs are unique, the rest of the attributes turn into arrays in
# order to allow multiple values or identifiers
add_attribute(list, argument, value)
else
Logger.error :parse, @code, @i, @j, :assignments_colon
end
else
unless list[argument]
default_value = for_definition ? 'nil' : 'true'
list[argument] = [:expression, default_value, { escaped: false }]
end
end
# If our attributes are wrapped, we allow method calls without
# paranthesis, ruby style, therefore we need a terminator to signify
# the expression end. If they are not wrapped (inline), we require
# paranthesis and allow inline calls
if wrapped
# Accept optional comma between attributes
accept_stripped :assignment_terminator
# Lookahead for attributes on the current line and the next one
if lookahead(:exp_identifier_stripped_lookahead)
attributes_assignments list, wrapped, for_definition
elsif lookahead_next_line(:exp_identifier_stripped_lookahead)
accept_newline
attributes_assignments list, wrapped, for_definition
end
elsif !wrapped && lookahead(:assignment_lookahead)
attributes_assignments list, wrapped, for_definition
end
list
end | [
"def",
"attributes_assignments",
"(",
"list",
",",
"wrapped",
"=",
"true",
",",
"for_definition",
"=",
"false",
")",
"if",
"wrapped",
"&&",
"lookahead",
"(",
":exp_identifier_stripped_lookahead",
")",
".",
"nil?",
"||",
"!",
"wrapped",
"&&",
"lookahead",
"(",
":assignment_lookahead",
")",
".",
"nil?",
"return",
"list",
"end",
"return",
"unless",
"(",
"argument",
"=",
"accept_stripped",
":node",
")",
"argument",
"=",
"argument",
".",
"to_sym",
"if",
"accept_stripped",
":assignment",
"escaped",
"=",
"if",
"accept",
":assignment_unescaped",
"false",
"else",
"true",
"end",
"if",
"(",
"value",
"=",
"expression",
"(",
"false",
",",
"wrapped",
")",
")",
"value",
"[",
"@options",
"]",
"[",
":escaped",
"]",
"=",
"escaped",
"add_attribute",
"(",
"list",
",",
"argument",
",",
"value",
")",
"else",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":assignments_colon",
"end",
"else",
"unless",
"list",
"[",
"argument",
"]",
"default_value",
"=",
"for_definition",
"?",
"'nil'",
":",
"'true'",
"list",
"[",
"argument",
"]",
"=",
"[",
":expression",
",",
"default_value",
",",
"{",
"escaped",
":",
"false",
"}",
"]",
"end",
"end",
"if",
"wrapped",
"accept_stripped",
":assignment_terminator",
"if",
"lookahead",
"(",
":exp_identifier_stripped_lookahead",
")",
"attributes_assignments",
"list",
",",
"wrapped",
",",
"for_definition",
"elsif",
"lookahead_next_line",
"(",
":exp_identifier_stripped_lookahead",
")",
"accept_newline",
"attributes_assignments",
"list",
",",
"wrapped",
",",
"for_definition",
"end",
"elsif",
"!",
"wrapped",
"&&",
"lookahead",
"(",
":assignment_lookahead",
")",
"attributes_assignments",
"list",
",",
"wrapped",
",",
"for_definition",
"end",
"list",
"end"
] | Get all attribute assignments as key=value pairs or standalone keys
[ assignments ]
@param list [Hash] Parent to which we append nodes
@param as_parameters [Boolean] Accept or reject identifier nodes | [
"Get",
"all",
"attribute",
"assignments",
"as",
"key",
"=",
"value",
"pairs",
"or",
"standalone",
"keys"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/node.rb#L226-L281 | train |
opulent/opulent | lib/opulent/parser/node.rb | Opulent.Parser.extend_attributes | def extend_attributes
return unless accept :extend_attributes
unescaped = accept :unescaped_value
extension = expression(false, false, false)
extension[@options][:escaped] = !unescaped
extension
end | ruby | def extend_attributes
return unless accept :extend_attributes
unescaped = accept :unescaped_value
extension = expression(false, false, false)
extension[@options][:escaped] = !unescaped
extension
end | [
"def",
"extend_attributes",
"return",
"unless",
"accept",
":extend_attributes",
"unescaped",
"=",
"accept",
":unescaped_value",
"extension",
"=",
"expression",
"(",
"false",
",",
"false",
",",
"false",
")",
"extension",
"[",
"@options",
"]",
"[",
":escaped",
"]",
"=",
"!",
"unescaped",
"extension",
"end"
] | Extend node attributes with hash from
+value
+{hash: "value"}
+(paranthesis) | [
"Extend",
"node",
"attributes",
"with",
"hash",
"from"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/node.rb#L289-L297 | train |
opulent/opulent | lib/opulent/parser/root.rb | Opulent.Parser.root | def root(parent = @root, min_indent = -1)
while (@line = @code[(@i += 1)])
# Reset character position cursor
@j = 0
# Skip to next iteration if we have a blank line
next if @line =~ /\A\s*\Z/
# Reset the line offset
@offset = 0
# Parse the current line by trying to match each node type towards it
# Add current indentation to the indent stack
indent = accept(:indent).size
# Stop using the current parent as root if it does not match the
# minimum indentation includements
unless min_indent < indent
@i -= 1
break
end
# If last include path had a greater indentation, pop the last file path
@file.pop if @file[-1][1] >= indent
# Try the main Opulent node types and process each one of them using
# their matching evaluation procedure
current_node = node(parent, indent) ||
text(parent, indent) ||
comment(parent, indent) ||
define(parent, indent) ||
control(parent, indent) ||
evaluate(parent, indent) ||
filter(parent, indent) ||
block_yield(parent, indent) ||
include_file(parent, indent) ||
html_text(parent, indent) ||
doctype(parent, indent)
# Throw an error if we couldn't find any valid node
unless current_node
Logger.error :parse, @code, @i, @j, :unknown_node_type
end
end
parent
end | ruby | def root(parent = @root, min_indent = -1)
while (@line = @code[(@i += 1)])
# Reset character position cursor
@j = 0
# Skip to next iteration if we have a blank line
next if @line =~ /\A\s*\Z/
# Reset the line offset
@offset = 0
# Parse the current line by trying to match each node type towards it
# Add current indentation to the indent stack
indent = accept(:indent).size
# Stop using the current parent as root if it does not match the
# minimum indentation includements
unless min_indent < indent
@i -= 1
break
end
# If last include path had a greater indentation, pop the last file path
@file.pop if @file[-1][1] >= indent
# Try the main Opulent node types and process each one of them using
# their matching evaluation procedure
current_node = node(parent, indent) ||
text(parent, indent) ||
comment(parent, indent) ||
define(parent, indent) ||
control(parent, indent) ||
evaluate(parent, indent) ||
filter(parent, indent) ||
block_yield(parent, indent) ||
include_file(parent, indent) ||
html_text(parent, indent) ||
doctype(parent, indent)
# Throw an error if we couldn't find any valid node
unless current_node
Logger.error :parse, @code, @i, @j, :unknown_node_type
end
end
parent
end | [
"def",
"root",
"(",
"parent",
"=",
"@root",
",",
"min_indent",
"=",
"-",
"1",
")",
"while",
"(",
"@line",
"=",
"@code",
"[",
"(",
"@i",
"+=",
"1",
")",
"]",
")",
"@j",
"=",
"0",
"next",
"if",
"@line",
"=~",
"/",
"\\A",
"\\s",
"\\Z",
"/",
"@offset",
"=",
"0",
"indent",
"=",
"accept",
"(",
":indent",
")",
".",
"size",
"unless",
"min_indent",
"<",
"indent",
"@i",
"-=",
"1",
"break",
"end",
"@file",
".",
"pop",
"if",
"@file",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
">=",
"indent",
"current_node",
"=",
"node",
"(",
"parent",
",",
"indent",
")",
"||",
"text",
"(",
"parent",
",",
"indent",
")",
"||",
"comment",
"(",
"parent",
",",
"indent",
")",
"||",
"define",
"(",
"parent",
",",
"indent",
")",
"||",
"control",
"(",
"parent",
",",
"indent",
")",
"||",
"evaluate",
"(",
"parent",
",",
"indent",
")",
"||",
"filter",
"(",
"parent",
",",
"indent",
")",
"||",
"block_yield",
"(",
"parent",
",",
"indent",
")",
"||",
"include_file",
"(",
"parent",
",",
"indent",
")",
"||",
"html_text",
"(",
"parent",
",",
"indent",
")",
"||",
"doctype",
"(",
"parent",
",",
"indent",
")",
"unless",
"current_node",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":unknown_node_type",
"end",
"end",
"parent",
"end"
] | Analyze the input code and check for matching tokens.
In case no match was found, throw an exception.
In special cases, modify the token hash.
@param parent [Array] Parent node to which we append to | [
"Analyze",
"the",
"input",
"code",
"and",
"check",
"for",
"matching",
"tokens",
".",
"In",
"case",
"no",
"match",
"was",
"found",
"throw",
"an",
"exception",
".",
"In",
"special",
"cases",
"modify",
"the",
"token",
"hash",
"."
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/root.rb#L11-L57 | train |
opulent/opulent | lib/opulent/compiler/define.rb | Opulent.Compiler.define | def define(node)
# Write out def method_name
definition = "def _opulent_definition_#{node[@value].to_s.tr '-', '_'}"
# Node attributes
parameters = []
node[@options][:parameters].each do |key, value|
parameters << "#{key} = #{value[@value]}"
end
parameters << 'attributes = {}'
parameters << 'indent'
parameters << '&block'
definition += '(' + parameters.join(', ') + ')'
buffer_eval 'instance_eval do'
buffer_eval definition
@in_definition = true
node[@children].each do |child|
root child, 0
end
@in_definition = false
buffer_eval 'end'
buffer_eval 'end'
end | ruby | def define(node)
# Write out def method_name
definition = "def _opulent_definition_#{node[@value].to_s.tr '-', '_'}"
# Node attributes
parameters = []
node[@options][:parameters].each do |key, value|
parameters << "#{key} = #{value[@value]}"
end
parameters << 'attributes = {}'
parameters << 'indent'
parameters << '&block'
definition += '(' + parameters.join(', ') + ')'
buffer_eval 'instance_eval do'
buffer_eval definition
@in_definition = true
node[@children].each do |child|
root child, 0
end
@in_definition = false
buffer_eval 'end'
buffer_eval 'end'
end | [
"def",
"define",
"(",
"node",
")",
"definition",
"=",
"\"def _opulent_definition_#{node[@value].to_s.tr '-', '_'}\"",
"parameters",
"=",
"[",
"]",
"node",
"[",
"@options",
"]",
"[",
":parameters",
"]",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"parameters",
"<<",
"\"#{key} = #{value[@value]}\"",
"end",
"parameters",
"<<",
"'attributes = {}'",
"parameters",
"<<",
"'indent'",
"parameters",
"<<",
"'&block'",
"definition",
"+=",
"'('",
"+",
"parameters",
".",
"join",
"(",
"', '",
")",
"+",
"')'",
"buffer_eval",
"'instance_eval do'",
"buffer_eval",
"definition",
"@in_definition",
"=",
"true",
"node",
"[",
"@children",
"]",
".",
"each",
"do",
"|",
"child",
"|",
"root",
"child",
",",
"0",
"end",
"@in_definition",
"=",
"false",
"buffer_eval",
"'end'",
"buffer_eval",
"'end'",
"end"
] | Write out definition node using ruby def
@param node [Node] Current node data with options | [
"Write",
"out",
"definition",
"node",
"using",
"ruby",
"def"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/compiler/define.rb#L9-L34 | train |
beatrichartz/configurations | lib/configurations/arbitrary.rb | Configurations.Arbitrary.respond_to_missing? | def respond_to_missing?(method, include_private = false)
__respond_to_writer?(method) ||
__respond_to_method_for_read?(method, *args, &block) ||
__respond_to_method_for_write?(method) ||
super
end | ruby | def respond_to_missing?(method, include_private = false)
__respond_to_writer?(method) ||
__respond_to_method_for_read?(method, *args, &block) ||
__respond_to_method_for_write?(method) ||
super
end | [
"def",
"respond_to_missing?",
"(",
"method",
",",
"include_private",
"=",
"false",
")",
"__respond_to_writer?",
"(",
"method",
")",
"||",
"__respond_to_method_for_read?",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"||",
"__respond_to_method_for_write?",
"(",
"method",
")",
"||",
"super",
"end"
] | Respond to missing according to the method_missing implementation | [
"Respond",
"to",
"missing",
"according",
"to",
"the",
"method_missing",
"implementation"
] | bd8ef480ca831e29b821ffc9ebeaed4ef46a9db2 | https://github.com/beatrichartz/configurations/blob/bd8ef480ca831e29b821ffc9ebeaed4ef46a9db2/lib/configurations/arbitrary.rb#L43-L48 | train |
opulent/opulent | lib/opulent/parser.rb | Opulent.Parser.apply_definitions | def apply_definitions(node)
# Apply definition check to all of the node's children
process_definitions = proc do |children|
children.each do |child|
# Check if we have a definition
is_definition = if child[@value] == @current_def
child[@options][:recursive]
else
@definitions.key?(child[@value])
end
# Set child as a defined node
child[@type] = :def if is_definition
# Recursively apply definitions to child nodes
apply_definitions child if child[@children]
end
end
# Apply definitions to each case of the control node
if [:if, :unless, :case].include? node[@type]
node[@children].each do |array|
process_definitions[array]
end
# Apply definition to all of the node's children
else
process_definitions[node[@children]]
end
end | ruby | def apply_definitions(node)
# Apply definition check to all of the node's children
process_definitions = proc do |children|
children.each do |child|
# Check if we have a definition
is_definition = if child[@value] == @current_def
child[@options][:recursive]
else
@definitions.key?(child[@value])
end
# Set child as a defined node
child[@type] = :def if is_definition
# Recursively apply definitions to child nodes
apply_definitions child if child[@children]
end
end
# Apply definitions to each case of the control node
if [:if, :unless, :case].include? node[@type]
node[@children].each do |array|
process_definitions[array]
end
# Apply definition to all of the node's children
else
process_definitions[node[@children]]
end
end | [
"def",
"apply_definitions",
"(",
"node",
")",
"process_definitions",
"=",
"proc",
"do",
"|",
"children",
"|",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"is_definition",
"=",
"if",
"child",
"[",
"@value",
"]",
"==",
"@current_def",
"child",
"[",
"@options",
"]",
"[",
":recursive",
"]",
"else",
"@definitions",
".",
"key?",
"(",
"child",
"[",
"@value",
"]",
")",
"end",
"child",
"[",
"@type",
"]",
"=",
":def",
"if",
"is_definition",
"apply_definitions",
"child",
"if",
"child",
"[",
"@children",
"]",
"end",
"end",
"if",
"[",
":if",
",",
":unless",
",",
":case",
"]",
".",
"include?",
"node",
"[",
"@type",
"]",
"node",
"[",
"@children",
"]",
".",
"each",
"do",
"|",
"array",
"|",
"process_definitions",
"[",
"array",
"]",
"end",
"else",
"process_definitions",
"[",
"node",
"[",
"@children",
"]",
"]",
"end",
"end"
] | Set each node as a defined node if a definition exists with the given
node name, unless we're inside a definition with the same name as the node
because we want to avoid recursion.
@param node [Node] Input Node to checked for existence of definitions | [
"Set",
"each",
"node",
"as",
"a",
"defined",
"node",
"if",
"a",
"definition",
"exists",
"with",
"the",
"given",
"node",
"name",
"unless",
"we",
"re",
"inside",
"a",
"definition",
"with",
"the",
"same",
"name",
"as",
"the",
"node",
"because",
"we",
"want",
"to",
"avoid",
"recursion",
"."
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser.rb#L93-L121 | train |
opulent/opulent | lib/opulent/parser.rb | Opulent.Parser.accept | def accept(token, required = false, strip = false)
# Consume leading whitespace if we want to ignore it
accept :whitespace if strip
# We reached the end of the parsing process and there are no more lines
# left to parse
return nil unless @line
# Match the token to the current line. If we find it, return the match.
# If it is required, signal an :expected error
if (match = @line[@offset..-1].match(Tokens[token]))
# Advance current offset with match length
@offset += match[0].size
@j += match[0].size
return match[0]
elsif required
Logger.error :parse, @code, @i, @j, :expected, token
end
end | ruby | def accept(token, required = false, strip = false)
# Consume leading whitespace if we want to ignore it
accept :whitespace if strip
# We reached the end of the parsing process and there are no more lines
# left to parse
return nil unless @line
# Match the token to the current line. If we find it, return the match.
# If it is required, signal an :expected error
if (match = @line[@offset..-1].match(Tokens[token]))
# Advance current offset with match length
@offset += match[0].size
@j += match[0].size
return match[0]
elsif required
Logger.error :parse, @code, @i, @j, :expected, token
end
end | [
"def",
"accept",
"(",
"token",
",",
"required",
"=",
"false",
",",
"strip",
"=",
"false",
")",
"accept",
":whitespace",
"if",
"strip",
"return",
"nil",
"unless",
"@line",
"if",
"(",
"match",
"=",
"@line",
"[",
"@offset",
"..",
"-",
"1",
"]",
".",
"match",
"(",
"Tokens",
"[",
"token",
"]",
")",
")",
"@offset",
"+=",
"match",
"[",
"0",
"]",
".",
"size",
"@j",
"+=",
"match",
"[",
"0",
"]",
".",
"size",
"return",
"match",
"[",
"0",
"]",
"elsif",
"required",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":expected",
",",
"token",
"end",
"end"
] | Check and accept or reject a given token as long as we have tokens
remaining. Shift the code with the match length plus any extra character
count around the capture group
@param token [RegEx] Token to be accepted by the parser
@param required [Boolean] Expect the given token syntax
@param strip [Boolean] Left strip the current code to remove whitespace | [
"Check",
"and",
"accept",
"or",
"reject",
"a",
"given",
"token",
"as",
"long",
"as",
"we",
"have",
"tokens",
"remaining",
".",
"Shift",
"the",
"code",
"with",
"the",
"match",
"length",
"plus",
"any",
"extra",
"character",
"count",
"around",
"the",
"capture",
"group"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser.rb#L131-L150 | train |
opulent/opulent | lib/opulent/parser.rb | Opulent.Parser.indent_lines | def indent_lines(text, indent)
text ||= ''
text.lines.map { |line| indent + line }.join
end | ruby | def indent_lines(text, indent)
text ||= ''
text.lines.map { |line| indent + line }.join
end | [
"def",
"indent_lines",
"(",
"text",
",",
"indent",
")",
"text",
"||=",
"''",
"text",
".",
"lines",
".",
"map",
"{",
"|",
"line",
"|",
"indent",
"+",
"line",
"}",
".",
"join",
"end"
] | Indent all lines of the input text using give indentation
@param text [String] Input text to be indented
@param indent [String] Indentation string to be appended | [
"Indent",
"all",
"lines",
"of",
"the",
"input",
"text",
"using",
"give",
"indentation"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser.rb#L210-L213 | train |
redbooth/redbooth-ruby | lib/redbooth-ruby/client.rb | RedboothRuby.Client.perform! | def perform!(resource_name, action, options = {})
ClientOperations::Perform.new(resource_name, action, session, options).perform!
end | ruby | def perform!(resource_name, action, options = {})
ClientOperations::Perform.new(resource_name, action, session, options).perform!
end | [
"def",
"perform!",
"(",
"resource_name",
",",
"action",
",",
"options",
"=",
"{",
"}",
")",
"ClientOperations",
"::",
"Perform",
".",
"new",
"(",
"resource_name",
",",
"action",
",",
"session",
",",
"options",
")",
".",
"perform!",
"end"
] | Executes block with the access token
@param [String||Symbol] resource_name name of the resource to execute over
@param [String||Symbol] action name of the action to execute over
@param [Hash] options for the execution
@return the execution return or nil | [
"Executes",
"block",
"with",
"the",
"access",
"token"
] | fb6bc228a9346d4db476032f0df16c9588fdfbe1 | https://github.com/redbooth/redbooth-ruby/blob/fb6bc228a9346d4db476032f0df16c9588fdfbe1/lib/redbooth-ruby/client.rb#L55-L57 | train |
Yellowen/Faalis | app/models/faalis/concerns/user/auth_definitions.rb | Faalis.Concerns::User::AuthDefinitions.password_required? | def password_required?
# TODO: nil? is not suitable for here we should use empty? or blink?
if Devise.omniauth_configs.any?
return (provider.nil? || password.nil?) && super
else
password.nil? && super
end
end | ruby | def password_required?
# TODO: nil? is not suitable for here we should use empty? or blink?
if Devise.omniauth_configs.any?
return (provider.nil? || password.nil?) && super
else
password.nil? && super
end
end | [
"def",
"password_required?",
"if",
"Devise",
".",
"omniauth_configs",
".",
"any?",
"return",
"(",
"provider",
".",
"nil?",
"||",
"password",
".",
"nil?",
")",
"&&",
"super",
"else",
"password",
".",
"nil?",
"&&",
"super",
"end",
"end"
] | Omniauth users does not need password | [
"Omniauth",
"users",
"does",
"not",
"need",
"password"
] | d12abdb8559dabbf6b2044e3ba437038527039b2 | https://github.com/Yellowen/Faalis/blob/d12abdb8559dabbf6b2044e3ba437038527039b2/app/models/faalis/concerns/user/auth_definitions.rb#L51-L58 | train |
redbooth/redbooth-ruby | lib/redbooth-ruby/file.rb | RedboothRuby.File.download | def download(style='original', path=nil)
options = { session: session }
options[:download_path] = path unless path.nil?
request = RedboothRuby.request(:download, nil, "files/#{id}/download/#{style}/#{name}", {}, options)
request.body
end | ruby | def download(style='original', path=nil)
options = { session: session }
options[:download_path] = path unless path.nil?
request = RedboothRuby.request(:download, nil, "files/#{id}/download/#{style}/#{name}", {}, options)
request.body
end | [
"def",
"download",
"(",
"style",
"=",
"'original'",
",",
"path",
"=",
"nil",
")",
"options",
"=",
"{",
"session",
":",
"session",
"}",
"options",
"[",
":download_path",
"]",
"=",
"path",
"unless",
"path",
".",
"nil?",
"request",
"=",
"RedboothRuby",
".",
"request",
"(",
":download",
",",
"nil",
",",
"\"files/#{id}/download/#{style}/#{name}\"",
",",
"{",
"}",
",",
"options",
")",
"request",
".",
"body",
"end"
] | Returns a blop with the file data
@param [String] style The style to use
@param [String] path The path to save the file to
@return [String] the object metadata | [
"Returns",
"a",
"blop",
"with",
"the",
"file",
"data"
] | fb6bc228a9346d4db476032f0df16c9588fdfbe1 | https://github.com/redbooth/redbooth-ruby/blob/fb6bc228a9346d4db476032f0df16c9588fdfbe1/lib/redbooth-ruby/file.rb#L32-L37 | train |
opulent/opulent | lib/opulent/engine.rb | Opulent.Engine.render | def render(scope = Object.new, locals = {}, &block)
# Get opulent buffer value
if scope.instance_variable_defined?(:@_opulent_buffer)
initial_buffer = scope.instance_variable_get(:@_opulent_buffer)
else
initial_buffer = []
end
# If a layout is set, get the specific layout, otherwise, set the default
# one. If a layout is set to false, the page will be render as it is.
if scope.is_a? binding.class
scope_object = eval 'self', scope
scope = scope_object.instance_eval { binding } if block_given?
else
scope_object = scope
scope = scope_object.instance_eval { binding }
end
# Set input local variables in current scope
if scope.respond_to? :local_variable_set
locals.each do |key, value|
scope.local_variable_set key, value
end
else
locals.each do |key, value|
eval("#{key} = nil; lambda {|v| #{key} = v}", scope).call(value)
end
end
# Evaluate the template in the given scope (context)
begin
eval @src, scope
rescue ::SyntaxError => e
raise SyntaxError, e.message
ensure
# Get rid of the current buffer
scope_object.instance_variable_set :@_opulent_buffer, initial_buffer
end
end | ruby | def render(scope = Object.new, locals = {}, &block)
# Get opulent buffer value
if scope.instance_variable_defined?(:@_opulent_buffer)
initial_buffer = scope.instance_variable_get(:@_opulent_buffer)
else
initial_buffer = []
end
# If a layout is set, get the specific layout, otherwise, set the default
# one. If a layout is set to false, the page will be render as it is.
if scope.is_a? binding.class
scope_object = eval 'self', scope
scope = scope_object.instance_eval { binding } if block_given?
else
scope_object = scope
scope = scope_object.instance_eval { binding }
end
# Set input local variables in current scope
if scope.respond_to? :local_variable_set
locals.each do |key, value|
scope.local_variable_set key, value
end
else
locals.each do |key, value|
eval("#{key} = nil; lambda {|v| #{key} = v}", scope).call(value)
end
end
# Evaluate the template in the given scope (context)
begin
eval @src, scope
rescue ::SyntaxError => e
raise SyntaxError, e.message
ensure
# Get rid of the current buffer
scope_object.instance_variable_set :@_opulent_buffer, initial_buffer
end
end | [
"def",
"render",
"(",
"scope",
"=",
"Object",
".",
"new",
",",
"locals",
"=",
"{",
"}",
",",
"&",
"block",
")",
"if",
"scope",
".",
"instance_variable_defined?",
"(",
":@_opulent_buffer",
")",
"initial_buffer",
"=",
"scope",
".",
"instance_variable_get",
"(",
":@_opulent_buffer",
")",
"else",
"initial_buffer",
"=",
"[",
"]",
"end",
"if",
"scope",
".",
"is_a?",
"binding",
".",
"class",
"scope_object",
"=",
"eval",
"'self'",
",",
"scope",
"scope",
"=",
"scope_object",
".",
"instance_eval",
"{",
"binding",
"}",
"if",
"block_given?",
"else",
"scope_object",
"=",
"scope",
"scope",
"=",
"scope_object",
".",
"instance_eval",
"{",
"binding",
"}",
"end",
"if",
"scope",
".",
"respond_to?",
":local_variable_set",
"locals",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"scope",
".",
"local_variable_set",
"key",
",",
"value",
"end",
"else",
"locals",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"eval",
"(",
"\"#{key} = nil; lambda {|v| #{key} = v}\"",
",",
"scope",
")",
".",
"call",
"(",
"value",
")",
"end",
"end",
"begin",
"eval",
"@src",
",",
"scope",
"rescue",
"::",
"SyntaxError",
"=>",
"e",
"raise",
"SyntaxError",
",",
"e",
".",
"message",
"ensure",
"scope_object",
".",
"instance_variable_set",
":@_opulent_buffer",
",",
"initial_buffer",
"end",
"end"
] | Update render settings
@param input [Symbol/String] Input code or file
@param settings [Hash] Opulent settings override
Avoid code duplication when layouting is set. When we have a layout, look
in layouts/application by default.
@param scope [Object] Template evaluation context
@param locals [Hash] Render call local variables
@param block [Proc] Processing environment data | [
"Update",
"render",
"settings"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/engine.rb#L50-L88 | train |
opulent/opulent | lib/opulent/engine.rb | Opulent.Engine.read | def read(input)
if input.is_a? Symbol
@file = File.expand_path get_eval_file input
File.read @file
else
@file = File.expand_path __FILE__
input
end
end | ruby | def read(input)
if input.is_a? Symbol
@file = File.expand_path get_eval_file input
File.read @file
else
@file = File.expand_path __FILE__
input
end
end | [
"def",
"read",
"(",
"input",
")",
"if",
"input",
".",
"is_a?",
"Symbol",
"@file",
"=",
"File",
".",
"expand_path",
"get_eval_file",
"input",
"File",
".",
"read",
"@file",
"else",
"@file",
"=",
"File",
".",
"expand_path",
"__FILE__",
"input",
"end",
"end"
] | Read input as file or string input
@param input [Object] | [
"Read",
"input",
"as",
"file",
"or",
"string",
"input"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/engine.rb#L96-L104 | train |
opulent/opulent | lib/opulent/engine.rb | Opulent.Engine.get_eval_file | def get_eval_file(input)
input = input.to_s
unless File.extname(input) == Settings::FILE_EXTENSION
input += Settings::FILE_EXTENSION
end
input
end | ruby | def get_eval_file(input)
input = input.to_s
unless File.extname(input) == Settings::FILE_EXTENSION
input += Settings::FILE_EXTENSION
end
input
end | [
"def",
"get_eval_file",
"(",
"input",
")",
"input",
"=",
"input",
".",
"to_s",
"unless",
"File",
".",
"extname",
"(",
"input",
")",
"==",
"Settings",
"::",
"FILE_EXTENSION",
"input",
"+=",
"Settings",
"::",
"FILE_EXTENSION",
"end",
"input",
"end"
] | Add .op extension to input file if it isn't already set.
@param input [Symbol] Input file | [
"Add",
".",
"op",
"extension",
"to",
"input",
"file",
"if",
"it",
"isn",
"t",
"already",
"set",
"."
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/engine.rb#L110-L116 | train |
opulent/opulent | lib/opulent/compiler/buffer.rb | Opulent.Compiler.buffer_attributes_to_hash | def buffer_attributes_to_hash(attributes)
'{' + attributes.inject([]) do |extend_map, (key, attribute)|
extend_map << (
":\"#{key}\" => " + if key == :class
'[' + attribute.map do |exp|
exp[@value]
end.join(', ') + ']'
else
attribute[@value]
end
)
end.join(', ') + '}'
end | ruby | def buffer_attributes_to_hash(attributes)
'{' + attributes.inject([]) do |extend_map, (key, attribute)|
extend_map << (
":\"#{key}\" => " + if key == :class
'[' + attribute.map do |exp|
exp[@value]
end.join(', ') + ']'
else
attribute[@value]
end
)
end.join(', ') + '}'
end | [
"def",
"buffer_attributes_to_hash",
"(",
"attributes",
")",
"'{'",
"+",
"attributes",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"extend_map",
",",
"(",
"key",
",",
"attribute",
")",
"|",
"extend_map",
"<<",
"(",
"\":\\\"#{key}\\\" => \"",
"+",
"if",
"key",
"==",
":class",
"'['",
"+",
"attribute",
".",
"map",
"do",
"|",
"exp",
"|",
"exp",
"[",
"@value",
"]",
"end",
".",
"join",
"(",
"', '",
")",
"+",
"']'",
"else",
"attribute",
"[",
"@value",
"]",
"end",
")",
"end",
".",
"join",
"(",
"', '",
")",
"+",
"'}'",
"end"
] | Turn call node attributes into a hash string
@param attributes [Array] Array of node attributes | [
"Turn",
"call",
"node",
"attributes",
"into",
"a",
"hash",
"string"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/compiler/buffer.rb#L88-L100 | train |
opulent/opulent | lib/opulent/compiler/buffer.rb | Opulent.Compiler.buffer_attributes | def buffer_attributes(attributes, extension)
# Proc for setting class attribute extension, used as DRY closure
#
buffer_class_attribute_type_check = proc do |variable, escape = true|
class_variable = buffer_set_variable :local, variable
# Check if we need to add the class attribute
buffer_eval "unless #{class_variable} and true === #{class_variable}"
# Check if class attribute has array value
buffer_eval "if Array === #{class_variable}"
ruby_code = "#{class_variable}.join ' '"
if escape
buffer_escape ruby_code
else
buffer ruby_code
end
# Check if class attribute has hash value
buffer_eval "elsif Hash === #{class_variable}"
ruby_code = "#{class_variable}.to_a.join ' '"
if escape
buffer_escape ruby_code
else
buffer ruby_code
end
# Other values
buffer_eval 'else'
ruby_code = "#{class_variable}"
if escape
buffer_escape ruby_code
else
buffer ruby_code
end
# End cases
buffer_eval 'end'
# End
buffer_eval 'end'
end
# Handle class attributes by checking if they're simple, noninterpolated
# strings or not and extend them if needed
#
buffer_class_attribute = proc do |attribute|
if attribute[@value] =~ Tokens[:exp_string_match]
buffer_split_by_interpolation attribute[@value][1..-2],
attribute[@options][:escaped]
else
buffer_class_attribute_type_check[
attribute[@value],
attribute[@options][:escaped]
]
end
end
# If we have class attributes, process each one and check if we have an
# extension for them
if attributes[:class]
buffer_freeze " class=\""
# Process every class attribute
attributes[:class].each do |node_class|
buffer_class_attribute[node_class]
buffer_freeze ' '
end
# Remove trailing whitespace from the buffer
buffer_remove_last_character
# Check for extension with :class key
if extension
buffer_eval "if #{extension[:name]}.has_key? :class"
buffer_freeze ' '
buffer_class_attribute_type_check[
"#{extension[:name]}.delete(:class)"
]
buffer_eval 'end'
end
buffer_freeze '"'
elsif extension
# If we do not have class attributes but we do have an extension, try to
# see if the extension contains a class attribute
buffer_eval "if #{extension[:name]}.has_key? :class"
buffer_freeze " class=\""
buffer_class_attribute_type_check["#{extension[:name]}.delete(:class)"]
buffer_freeze '"'
buffer_eval 'end'
end
# Proc for setting class attribute extension, used as DRY closure
#
buffer_data_attribute_type_check = proc do |key, variable, escape = true, dynamic = false|
# Check if variable is set
buffer_eval "if #{variable}"
# @Array
buffer_eval "if Array === #{variable}"
dynamic ? buffer("\" #{key}=\\\"\"") : buffer_freeze(" #{key}=\"")
ruby_code = "#{variable}.join '_'"
if escape
buffer_escape ruby_code
else
buffer ruby_code
end
buffer_freeze '"'
# @Hash
buffer_eval "elsif Hash === #{variable}"
buffer_eval "#{variable}.each do |#{OPULENT_KEY}, #{OPULENT_VALUE}|"
# key-hashkey
dynamic ? buffer("\" #{key}-\"") : buffer_freeze(" #{key}-")
buffer "#{OPULENT_KEY}.to_s"
#="value"
buffer_freeze "=\""
escape ? buffer_escape(OPULENT_VALUE) : buffer(OPULENT_VALUE)
buffer_freeze '"'
buffer_eval 'end'
# @TrueClass
buffer_eval "elsif true === #{variable}"
dynamic ? buffer("\" #{key}\"") : buffer_freeze(" #{key}")
# @Object
buffer_eval 'else'
dynamic ? buffer("\" #{key}=\\\"\"") : buffer_freeze(" #{key}=\"")
escape ? buffer_escape("#{variable}") : buffer("#{variable}")
buffer_freeze '"'
# End Cases
buffer_eval 'end'
# End
buffer_eval 'end'
end
# Handle data (normal) attributes by checking if they're simple, noninterpolated
# strings and extend them if needed
#
buffer_data_attribute = proc do |key, attribute|
# When we have an extension for our attributes, check current key.
# If it exists, check it's type and generate everything dynamically
if extension
buffer_eval "if #{extension[:name]}.has_key? :\"#{key}\""
variable = buffer_set_variable :local,
"#{extension[:name]}" \
".delete(:\"#{key}\")"
buffer_data_attribute_type_check[
key,
variable,
attribute[@options][:escaped]
]
buffer_eval 'else'
end
# Check if the set attribute is a simple string. If it is, freeze it or
# escape it. Otherwise, evaluate and initialize the type check.
if attribute[@value] =~ Tokens[:exp_string_match]
buffer_freeze " #{key}=\""
buffer_split_by_interpolation attribute[@value][1..-2],
attribute[@options][:escaped]
buffer_freeze "\""
else
# Evaluate and type check
variable = buffer_set_variable :local, attribute[@value]
buffer_data_attribute_type_check[
key,
variable,
attribute[@options][:escaped]
]
end
# Extension end
buffer_eval 'end' if extension
end
# Process the remaining, non-class related attributes
attributes.each do |key, attribute|
next if key == :class
buffer_data_attribute[key, attribute]
end
# Process remaining extension keys if there are any
return unless extension
buffer_eval "#{extension[:name]}.each do " \
"|ext#{OPULENT_KEY}, ext#{OPULENT_VALUE}|"
buffer_data_attribute_type_check[
"\#{ext#{OPULENT_KEY}}",
"ext#{OPULENT_VALUE}",
extension[:escaped],
true
]
buffer_eval 'end'
end | ruby | def buffer_attributes(attributes, extension)
# Proc for setting class attribute extension, used as DRY closure
#
buffer_class_attribute_type_check = proc do |variable, escape = true|
class_variable = buffer_set_variable :local, variable
# Check if we need to add the class attribute
buffer_eval "unless #{class_variable} and true === #{class_variable}"
# Check if class attribute has array value
buffer_eval "if Array === #{class_variable}"
ruby_code = "#{class_variable}.join ' '"
if escape
buffer_escape ruby_code
else
buffer ruby_code
end
# Check if class attribute has hash value
buffer_eval "elsif Hash === #{class_variable}"
ruby_code = "#{class_variable}.to_a.join ' '"
if escape
buffer_escape ruby_code
else
buffer ruby_code
end
# Other values
buffer_eval 'else'
ruby_code = "#{class_variable}"
if escape
buffer_escape ruby_code
else
buffer ruby_code
end
# End cases
buffer_eval 'end'
# End
buffer_eval 'end'
end
# Handle class attributes by checking if they're simple, noninterpolated
# strings or not and extend them if needed
#
buffer_class_attribute = proc do |attribute|
if attribute[@value] =~ Tokens[:exp_string_match]
buffer_split_by_interpolation attribute[@value][1..-2],
attribute[@options][:escaped]
else
buffer_class_attribute_type_check[
attribute[@value],
attribute[@options][:escaped]
]
end
end
# If we have class attributes, process each one and check if we have an
# extension for them
if attributes[:class]
buffer_freeze " class=\""
# Process every class attribute
attributes[:class].each do |node_class|
buffer_class_attribute[node_class]
buffer_freeze ' '
end
# Remove trailing whitespace from the buffer
buffer_remove_last_character
# Check for extension with :class key
if extension
buffer_eval "if #{extension[:name]}.has_key? :class"
buffer_freeze ' '
buffer_class_attribute_type_check[
"#{extension[:name]}.delete(:class)"
]
buffer_eval 'end'
end
buffer_freeze '"'
elsif extension
# If we do not have class attributes but we do have an extension, try to
# see if the extension contains a class attribute
buffer_eval "if #{extension[:name]}.has_key? :class"
buffer_freeze " class=\""
buffer_class_attribute_type_check["#{extension[:name]}.delete(:class)"]
buffer_freeze '"'
buffer_eval 'end'
end
# Proc for setting class attribute extension, used as DRY closure
#
buffer_data_attribute_type_check = proc do |key, variable, escape = true, dynamic = false|
# Check if variable is set
buffer_eval "if #{variable}"
# @Array
buffer_eval "if Array === #{variable}"
dynamic ? buffer("\" #{key}=\\\"\"") : buffer_freeze(" #{key}=\"")
ruby_code = "#{variable}.join '_'"
if escape
buffer_escape ruby_code
else
buffer ruby_code
end
buffer_freeze '"'
# @Hash
buffer_eval "elsif Hash === #{variable}"
buffer_eval "#{variable}.each do |#{OPULENT_KEY}, #{OPULENT_VALUE}|"
# key-hashkey
dynamic ? buffer("\" #{key}-\"") : buffer_freeze(" #{key}-")
buffer "#{OPULENT_KEY}.to_s"
#="value"
buffer_freeze "=\""
escape ? buffer_escape(OPULENT_VALUE) : buffer(OPULENT_VALUE)
buffer_freeze '"'
buffer_eval 'end'
# @TrueClass
buffer_eval "elsif true === #{variable}"
dynamic ? buffer("\" #{key}\"") : buffer_freeze(" #{key}")
# @Object
buffer_eval 'else'
dynamic ? buffer("\" #{key}=\\\"\"") : buffer_freeze(" #{key}=\"")
escape ? buffer_escape("#{variable}") : buffer("#{variable}")
buffer_freeze '"'
# End Cases
buffer_eval 'end'
# End
buffer_eval 'end'
end
# Handle data (normal) attributes by checking if they're simple, noninterpolated
# strings and extend them if needed
#
buffer_data_attribute = proc do |key, attribute|
# When we have an extension for our attributes, check current key.
# If it exists, check it's type and generate everything dynamically
if extension
buffer_eval "if #{extension[:name]}.has_key? :\"#{key}\""
variable = buffer_set_variable :local,
"#{extension[:name]}" \
".delete(:\"#{key}\")"
buffer_data_attribute_type_check[
key,
variable,
attribute[@options][:escaped]
]
buffer_eval 'else'
end
# Check if the set attribute is a simple string. If it is, freeze it or
# escape it. Otherwise, evaluate and initialize the type check.
if attribute[@value] =~ Tokens[:exp_string_match]
buffer_freeze " #{key}=\""
buffer_split_by_interpolation attribute[@value][1..-2],
attribute[@options][:escaped]
buffer_freeze "\""
else
# Evaluate and type check
variable = buffer_set_variable :local, attribute[@value]
buffer_data_attribute_type_check[
key,
variable,
attribute[@options][:escaped]
]
end
# Extension end
buffer_eval 'end' if extension
end
# Process the remaining, non-class related attributes
attributes.each do |key, attribute|
next if key == :class
buffer_data_attribute[key, attribute]
end
# Process remaining extension keys if there are any
return unless extension
buffer_eval "#{extension[:name]}.each do " \
"|ext#{OPULENT_KEY}, ext#{OPULENT_VALUE}|"
buffer_data_attribute_type_check[
"\#{ext#{OPULENT_KEY}}",
"ext#{OPULENT_VALUE}",
extension[:escaped],
true
]
buffer_eval 'end'
end | [
"def",
"buffer_attributes",
"(",
"attributes",
",",
"extension",
")",
"buffer_class_attribute_type_check",
"=",
"proc",
"do",
"|",
"variable",
",",
"escape",
"=",
"true",
"|",
"class_variable",
"=",
"buffer_set_variable",
":local",
",",
"variable",
"buffer_eval",
"\"unless #{class_variable} and true === #{class_variable}\"",
"buffer_eval",
"\"if Array === #{class_variable}\"",
"ruby_code",
"=",
"\"#{class_variable}.join ' '\"",
"if",
"escape",
"buffer_escape",
"ruby_code",
"else",
"buffer",
"ruby_code",
"end",
"buffer_eval",
"\"elsif Hash === #{class_variable}\"",
"ruby_code",
"=",
"\"#{class_variable}.to_a.join ' '\"",
"if",
"escape",
"buffer_escape",
"ruby_code",
"else",
"buffer",
"ruby_code",
"end",
"buffer_eval",
"'else'",
"ruby_code",
"=",
"\"#{class_variable}\"",
"if",
"escape",
"buffer_escape",
"ruby_code",
"else",
"buffer",
"ruby_code",
"end",
"buffer_eval",
"'end'",
"buffer_eval",
"'end'",
"end",
"buffer_class_attribute",
"=",
"proc",
"do",
"|",
"attribute",
"|",
"if",
"attribute",
"[",
"@value",
"]",
"=~",
"Tokens",
"[",
":exp_string_match",
"]",
"buffer_split_by_interpolation",
"attribute",
"[",
"@value",
"]",
"[",
"1",
"..",
"-",
"2",
"]",
",",
"attribute",
"[",
"@options",
"]",
"[",
":escaped",
"]",
"else",
"buffer_class_attribute_type_check",
"[",
"attribute",
"[",
"@value",
"]",
",",
"attribute",
"[",
"@options",
"]",
"[",
":escaped",
"]",
"]",
"end",
"end",
"if",
"attributes",
"[",
":class",
"]",
"buffer_freeze",
"\" class=\\\"\"",
"attributes",
"[",
":class",
"]",
".",
"each",
"do",
"|",
"node_class",
"|",
"buffer_class_attribute",
"[",
"node_class",
"]",
"buffer_freeze",
"' '",
"end",
"buffer_remove_last_character",
"if",
"extension",
"buffer_eval",
"\"if #{extension[:name]}.has_key? :class\"",
"buffer_freeze",
"' '",
"buffer_class_attribute_type_check",
"[",
"\"#{extension[:name]}.delete(:class)\"",
"]",
"buffer_eval",
"'end'",
"end",
"buffer_freeze",
"'\"'",
"elsif",
"extension",
"buffer_eval",
"\"if #{extension[:name]}.has_key? :class\"",
"buffer_freeze",
"\" class=\\\"\"",
"buffer_class_attribute_type_check",
"[",
"\"#{extension[:name]}.delete(:class)\"",
"]",
"buffer_freeze",
"'\"'",
"buffer_eval",
"'end'",
"end",
"buffer_data_attribute_type_check",
"=",
"proc",
"do",
"|",
"key",
",",
"variable",
",",
"escape",
"=",
"true",
",",
"dynamic",
"=",
"false",
"|",
"buffer_eval",
"\"if #{variable}\"",
"buffer_eval",
"\"if Array === #{variable}\"",
"dynamic",
"?",
"buffer",
"(",
"\"\\\" #{key}=\\\\\\\"\\\"\"",
")",
":",
"buffer_freeze",
"(",
"\" #{key}=\\\"\"",
")",
"ruby_code",
"=",
"\"#{variable}.join '_'\"",
"if",
"escape",
"buffer_escape",
"ruby_code",
"else",
"buffer",
"ruby_code",
"end",
"buffer_freeze",
"'\"'",
"buffer_eval",
"\"elsif Hash === #{variable}\"",
"buffer_eval",
"\"#{variable}.each do |#{OPULENT_KEY}, #{OPULENT_VALUE}|\"",
"dynamic",
"?",
"buffer",
"(",
"\"\\\" #{key}-\\\"\"",
")",
":",
"buffer_freeze",
"(",
"\" #{key}-\"",
")",
"buffer",
"\"#{OPULENT_KEY}.to_s\"",
"buffer_freeze",
"\"=\\\"\"",
"escape",
"?",
"buffer_escape",
"(",
"OPULENT_VALUE",
")",
":",
"buffer",
"(",
"OPULENT_VALUE",
")",
"buffer_freeze",
"'\"'",
"buffer_eval",
"'end'",
"buffer_eval",
"\"elsif true === #{variable}\"",
"dynamic",
"?",
"buffer",
"(",
"\"\\\" #{key}\\\"\"",
")",
":",
"buffer_freeze",
"(",
"\" #{key}\"",
")",
"buffer_eval",
"'else'",
"dynamic",
"?",
"buffer",
"(",
"\"\\\" #{key}=\\\\\\\"\\\"\"",
")",
":",
"buffer_freeze",
"(",
"\" #{key}=\\\"\"",
")",
"escape",
"?",
"buffer_escape",
"(",
"\"#{variable}\"",
")",
":",
"buffer",
"(",
"\"#{variable}\"",
")",
"buffer_freeze",
"'\"'",
"buffer_eval",
"'end'",
"buffer_eval",
"'end'",
"end",
"buffer_data_attribute",
"=",
"proc",
"do",
"|",
"key",
",",
"attribute",
"|",
"if",
"extension",
"buffer_eval",
"\"if #{extension[:name]}.has_key? :\\\"#{key}\\\"\"",
"variable",
"=",
"buffer_set_variable",
":local",
",",
"\"#{extension[:name]}\"",
"\".delete(:\\\"#{key}\\\")\"",
"buffer_data_attribute_type_check",
"[",
"key",
",",
"variable",
",",
"attribute",
"[",
"@options",
"]",
"[",
":escaped",
"]",
"]",
"buffer_eval",
"'else'",
"end",
"if",
"attribute",
"[",
"@value",
"]",
"=~",
"Tokens",
"[",
":exp_string_match",
"]",
"buffer_freeze",
"\" #{key}=\\\"\"",
"buffer_split_by_interpolation",
"attribute",
"[",
"@value",
"]",
"[",
"1",
"..",
"-",
"2",
"]",
",",
"attribute",
"[",
"@options",
"]",
"[",
":escaped",
"]",
"buffer_freeze",
"\"\\\"\"",
"else",
"variable",
"=",
"buffer_set_variable",
":local",
",",
"attribute",
"[",
"@value",
"]",
"buffer_data_attribute_type_check",
"[",
"key",
",",
"variable",
",",
"attribute",
"[",
"@options",
"]",
"[",
":escaped",
"]",
"]",
"end",
"buffer_eval",
"'end'",
"if",
"extension",
"end",
"attributes",
".",
"each",
"do",
"|",
"key",
",",
"attribute",
"|",
"next",
"if",
"key",
"==",
":class",
"buffer_data_attribute",
"[",
"key",
",",
"attribute",
"]",
"end",
"return",
"unless",
"extension",
"buffer_eval",
"\"#{extension[:name]}.each do \"",
"\"|ext#{OPULENT_KEY}, ext#{OPULENT_VALUE}|\"",
"buffer_data_attribute_type_check",
"[",
"\"\\#{ext#{OPULENT_KEY}}\"",
",",
"\"ext#{OPULENT_VALUE}\"",
",",
"extension",
"[",
":escaped",
"]",
",",
"true",
"]",
"buffer_eval",
"'end'",
"end"
] | Go through the node attributes and apply extension where needed
@param attributes [Array] Array of node attributes, from parser
@param extension [String] Extension identifier | [
"Go",
"through",
"the",
"node",
"attributes",
"and",
"apply",
"extension",
"where",
"needed"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/compiler/buffer.rb#L107-L307 | train |
opulent/opulent | lib/opulent/compiler/buffer.rb | Opulent.Compiler.buffer_split_by_interpolation | def buffer_split_by_interpolation(string, escape = true)
# Interpolate variables in text (#{variable}).
# Split the text into multiple dynamic and static parts.
begin
case string
when /\A\\\#\{/
# Escaped interpolation
buffer_freeze '#{'
string = $'
when /\A#\{((?>[^{}]|(\{(?>[^{}]|\g<1>)*\}))*)\}/
# Interpolation
string = $'
code = $1
# escape = code !~ /\A\{.*\}\Z/
if escape
buffer_escape code
else
buffer code
end
when /\A([\\#]?[^#\\]*([#\\][^\\#\{][^#\\]*)*)/
string_remaining = $'
string_current = $&
# Static text
if escape && string_current =~ Utils::ESCAPE_HTML_PATTERN
buffer_escape string_current.inspect
else
buffer_freeze string_current
end
string = string_remaining
end
end until string.empty?
end | ruby | def buffer_split_by_interpolation(string, escape = true)
# Interpolate variables in text (#{variable}).
# Split the text into multiple dynamic and static parts.
begin
case string
when /\A\\\#\{/
# Escaped interpolation
buffer_freeze '#{'
string = $'
when /\A#\{((?>[^{}]|(\{(?>[^{}]|\g<1>)*\}))*)\}/
# Interpolation
string = $'
code = $1
# escape = code !~ /\A\{.*\}\Z/
if escape
buffer_escape code
else
buffer code
end
when /\A([\\#]?[^#\\]*([#\\][^\\#\{][^#\\]*)*)/
string_remaining = $'
string_current = $&
# Static text
if escape && string_current =~ Utils::ESCAPE_HTML_PATTERN
buffer_escape string_current.inspect
else
buffer_freeze string_current
end
string = string_remaining
end
end until string.empty?
end | [
"def",
"buffer_split_by_interpolation",
"(",
"string",
",",
"escape",
"=",
"true",
")",
"begin",
"case",
"string",
"when",
"/",
"\\A",
"\\\\",
"\\#",
"\\{",
"/",
"buffer_freeze",
"'#{'",
"string",
"=",
"$'",
"when",
"/",
"\\A",
"\\{",
"\\{",
"\\g",
"\\}",
"\\}",
"/",
"string",
"=",
"$'",
"code",
"=",
"$1",
"if",
"escape",
"buffer_escape",
"code",
"else",
"buffer",
"code",
"end",
"when",
"/",
"\\A",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\{",
"\\\\",
"/",
"string_remaining",
"=",
"$'",
"string_current",
"=",
"$&",
"if",
"escape",
"&&",
"string_current",
"=~",
"Utils",
"::",
"ESCAPE_HTML_PATTERN",
"buffer_escape",
"string_current",
".",
"inspect",
"else",
"buffer_freeze",
"string_current",
"end",
"string",
"=",
"string_remaining",
"end",
"end",
"until",
"string",
".",
"empty?",
"end"
] | Split a string by its interpolation, then check if it really needs to be
escaped or not. Huge performance boost!
@param string [String] Input string
@param escape [Boolean] Escape string
@ref slim-lang Thank you for the interpolation code | [
"Split",
"a",
"string",
"by",
"its",
"interpolation",
"then",
"check",
"if",
"it",
"really",
"needs",
"to",
"be",
"escaped",
"or",
"not",
".",
"Huge",
"performance",
"boost!"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/compiler/buffer.rb#L339-L373 | train |
beatrichartz/configurations | lib/configurations/strict.rb | Configurations.Strict.__evaluate_configurable! | def __evaluate_configurable!
entries = @properties.entries_at(@path)
entries.each do |property, value|
if value.is_a?(Maps::Properties::Entry)
__install_property__(property)
else
__install_nested_getter__(property)
end
end
end | ruby | def __evaluate_configurable!
entries = @properties.entries_at(@path)
entries.each do |property, value|
if value.is_a?(Maps::Properties::Entry)
__install_property__(property)
else
__install_nested_getter__(property)
end
end
end | [
"def",
"__evaluate_configurable!",
"entries",
"=",
"@properties",
".",
"entries_at",
"(",
"@path",
")",
"entries",
".",
"each",
"do",
"|",
"property",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"(",
"Maps",
"::",
"Properties",
"::",
"Entry",
")",
"__install_property__",
"(",
"property",
")",
"else",
"__install_nested_getter__",
"(",
"property",
")",
"end",
"end",
"end"
] | Evaluates configurable properties and passes eventual hashes
down to subconfigurations | [
"Evaluates",
"configurable",
"properties",
"and",
"passes",
"eventual",
"hashes",
"down",
"to",
"subconfigurations"
] | bd8ef480ca831e29b821ffc9ebeaed4ef46a9db2 | https://github.com/beatrichartz/configurations/blob/bd8ef480ca831e29b821ffc9ebeaed4ef46a9db2/lib/configurations/strict.rb#L36-L45 | train |
beatrichartz/configurations | lib/configurations/strict.rb | Configurations.Strict.__assign! | def __assign!(property, value)
@types.test!(@path.add(property), value)
v = @blocks.evaluate!(@path.add(property), value)
value = v unless v.nil?
super(property, value)
end | ruby | def __assign!(property, value)
@types.test!(@path.add(property), value)
v = @blocks.evaluate!(@path.add(property), value)
value = v unless v.nil?
super(property, value)
end | [
"def",
"__assign!",
"(",
"property",
",",
"value",
")",
"@types",
".",
"test!",
"(",
"@path",
".",
"add",
"(",
"property",
")",
",",
"value",
")",
"v",
"=",
"@blocks",
".",
"evaluate!",
"(",
"@path",
".",
"add",
"(",
"property",
")",
",",
"value",
")",
"value",
"=",
"v",
"unless",
"v",
".",
"nil?",
"super",
"(",
"property",
",",
"value",
")",
"end"
] | Assigns a value after running the assertions
@param [Symbol] property the property to type test
@param [Any] value the given value | [
"Assigns",
"a",
"value",
"after",
"running",
"the",
"assertions"
] | bd8ef480ca831e29b821ffc9ebeaed4ef46a9db2 | https://github.com/beatrichartz/configurations/blob/bd8ef480ca831e29b821ffc9ebeaed4ef46a9db2/lib/configurations/strict.rb#L109-L115 | train |
mdub/representative | lib/representative/abstract_xml.rb | Representative.AbstractXml.element | def element(name, *args, &block)
metadata = @inspector.get_metadata(current_subject, name)
attributes = args.extract_options!.merge(metadata)
subject_of_element = if args.empty?
@inspector.get_value(current_subject, name)
else
args.shift
end
raise ArgumentError, "too many arguments" unless args.empty?
representing(subject_of_element) do
resolved_attributes = resolve_attributes(attributes)
content_string = content_block = nil
unless current_subject.nil?
if block
unless block == Representative::EMPTY
content_block = Proc.new { block.call(current_subject) }
end
else
content_string = current_subject.to_s
end
end
generate_element(format_name(name), resolved_attributes, content_string, &content_block)
end
end | ruby | def element(name, *args, &block)
metadata = @inspector.get_metadata(current_subject, name)
attributes = args.extract_options!.merge(metadata)
subject_of_element = if args.empty?
@inspector.get_value(current_subject, name)
else
args.shift
end
raise ArgumentError, "too many arguments" unless args.empty?
representing(subject_of_element) do
resolved_attributes = resolve_attributes(attributes)
content_string = content_block = nil
unless current_subject.nil?
if block
unless block == Representative::EMPTY
content_block = Proc.new { block.call(current_subject) }
end
else
content_string = current_subject.to_s
end
end
generate_element(format_name(name), resolved_attributes, content_string, &content_block)
end
end | [
"def",
"element",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"metadata",
"=",
"@inspector",
".",
"get_metadata",
"(",
"current_subject",
",",
"name",
")",
"attributes",
"=",
"args",
".",
"extract_options!",
".",
"merge",
"(",
"metadata",
")",
"subject_of_element",
"=",
"if",
"args",
".",
"empty?",
"@inspector",
".",
"get_value",
"(",
"current_subject",
",",
"name",
")",
"else",
"args",
".",
"shift",
"end",
"raise",
"ArgumentError",
",",
"\"too many arguments\"",
"unless",
"args",
".",
"empty?",
"representing",
"(",
"subject_of_element",
")",
"do",
"resolved_attributes",
"=",
"resolve_attributes",
"(",
"attributes",
")",
"content_string",
"=",
"content_block",
"=",
"nil",
"unless",
"current_subject",
".",
"nil?",
"if",
"block",
"unless",
"block",
"==",
"Representative",
"::",
"EMPTY",
"content_block",
"=",
"Proc",
".",
"new",
"{",
"block",
".",
"call",
"(",
"current_subject",
")",
"}",
"end",
"else",
"content_string",
"=",
"current_subject",
".",
"to_s",
"end",
"end",
"generate_element",
"(",
"format_name",
"(",
"name",
")",
",",
"resolved_attributes",
",",
"content_string",
",",
"&",
"content_block",
")",
"end",
"end"
] | Generate an element.
With two arguments, it generates an element with the specified text content.
r.element :size, 42
# => <size>42</size>
More commonly, though, the second argument is omitted, in which case the
element content is assumed to be the named property of the current #subject.
r.representing my_shoe do
r.element :size
end
# => <size>9</size>
If a block is attached, nested elements can be generated. The element "value"
(whether explicitly provided, or derived from the current subject) becomes the
subject during evaluation of the block.
r.element :book, book do
r.title
r.author
end
# => <book><title>Whatever</title><author>Whoever</author></book>
Providing a final Hash argument specifies element attributes.
r.element :size, :type => "integer"
# => <size type="integer">9</size> | [
"Generate",
"an",
"element",
"."
] | c60214e79d51581a1744ae2891094468416b88f9 | https://github.com/mdub/representative/blob/c60214e79d51581a1744ae2891094468416b88f9/lib/representative/abstract_xml.rb#L45-L77 | train |
mdub/representative | lib/representative/abstract_xml.rb | Representative.AbstractXml.list_of | def list_of(name, *args, &block)
options = args.extract_options!
list_subject = args.empty? ? name : args.shift
raise ArgumentError, "too many arguments" unless args.empty?
list_attributes = options[:list_attributes] || {}
item_name = options[:item_name] || name.to_s.singularize
item_attributes = options[:item_attributes] || {}
items = resolve_value(list_subject)
element(name, items, list_attributes.merge(:type => proc{"array"})) do
items.each do |item|
element(item_name, item, item_attributes, &block)
end
end
end | ruby | def list_of(name, *args, &block)
options = args.extract_options!
list_subject = args.empty? ? name : args.shift
raise ArgumentError, "too many arguments" unless args.empty?
list_attributes = options[:list_attributes] || {}
item_name = options[:item_name] || name.to_s.singularize
item_attributes = options[:item_attributes] || {}
items = resolve_value(list_subject)
element(name, items, list_attributes.merge(:type => proc{"array"})) do
items.each do |item|
element(item_name, item, item_attributes, &block)
end
end
end | [
"def",
"list_of",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"options",
"=",
"args",
".",
"extract_options!",
"list_subject",
"=",
"args",
".",
"empty?",
"?",
"name",
":",
"args",
".",
"shift",
"raise",
"ArgumentError",
",",
"\"too many arguments\"",
"unless",
"args",
".",
"empty?",
"list_attributes",
"=",
"options",
"[",
":list_attributes",
"]",
"||",
"{",
"}",
"item_name",
"=",
"options",
"[",
":item_name",
"]",
"||",
"name",
".",
"to_s",
".",
"singularize",
"item_attributes",
"=",
"options",
"[",
":item_attributes",
"]",
"||",
"{",
"}",
"items",
"=",
"resolve_value",
"(",
"list_subject",
")",
"element",
"(",
"name",
",",
"items",
",",
"list_attributes",
".",
"merge",
"(",
":type",
"=>",
"proc",
"{",
"\"array\"",
"}",
")",
")",
"do",
"items",
".",
"each",
"do",
"|",
"item",
"|",
"element",
"(",
"item_name",
",",
"item",
",",
"item_attributes",
",",
"&",
"block",
")",
"end",
"end",
"end"
] | Generate a list of elements from Enumerable data.
r.list_of :books, my_books do
r.element :title
end
# => <books type="array">
# <book><title>Sailing for old dogs</title></book>
# <book><title>On the horizon</title></book>
# <book><title>The Little Blue Book of VHS Programming</title></book>
# </books>
Like #element, the value can be explicit, but is more commonly extracted
by name from the current #subject. | [
"Generate",
"a",
"list",
"of",
"elements",
"from",
"Enumerable",
"data",
"."
] | c60214e79d51581a1744ae2891094468416b88f9 | https://github.com/mdub/representative/blob/c60214e79d51581a1744ae2891094468416b88f9/lib/representative/abstract_xml.rb#L93-L110 | train |
opulent/opulent | lib/opulent/parser/expression.rb | Opulent.Parser.expression | def expression(allow_assignments = true, wrapped = true, whitespace = true)
buffer = ''
# Build a ruby expression out of accepted literals
while (term = (whitespace ? accept(:whitespace) : nil) ||
modifier ||
identifier ||
method_call ||
paranthesis ||
array ||
hash ||
symbol ||
percent ||
primary_term)
buffer += term
# Accept operations which have a right term and raise an error if
# we have an unfinished expression such as "a +", "b - 1 >" and other
# expressions following the same pattern
if wrapped && (op = operation ||
(allow_assignments ? accept_stripped(:exp_assignment) : nil))
buffer += op
if (right_term = expression(allow_assignments, wrapped)).nil?
Logger.error :parse, @code, @i, @j, :expression
else
buffer += right_term[@value]
end
elsif (op = array || op = method_call || op = ternary_operator(allow_assignments, wrapped))
buffer += op
end
# Do not continue if the expression has whitespace method calls in
# an unwrapped context because this will confuse the parser
unless buffer.strip.empty?
break if lookahead(:exp_identifier_lookahead).nil?
end
end
if buffer.strip.empty?
undo buffer
else
[:expression, buffer.strip, {}]
end
end | ruby | def expression(allow_assignments = true, wrapped = true, whitespace = true)
buffer = ''
# Build a ruby expression out of accepted literals
while (term = (whitespace ? accept(:whitespace) : nil) ||
modifier ||
identifier ||
method_call ||
paranthesis ||
array ||
hash ||
symbol ||
percent ||
primary_term)
buffer += term
# Accept operations which have a right term and raise an error if
# we have an unfinished expression such as "a +", "b - 1 >" and other
# expressions following the same pattern
if wrapped && (op = operation ||
(allow_assignments ? accept_stripped(:exp_assignment) : nil))
buffer += op
if (right_term = expression(allow_assignments, wrapped)).nil?
Logger.error :parse, @code, @i, @j, :expression
else
buffer += right_term[@value]
end
elsif (op = array || op = method_call || op = ternary_operator(allow_assignments, wrapped))
buffer += op
end
# Do not continue if the expression has whitespace method calls in
# an unwrapped context because this will confuse the parser
unless buffer.strip.empty?
break if lookahead(:exp_identifier_lookahead).nil?
end
end
if buffer.strip.empty?
undo buffer
else
[:expression, buffer.strip, {}]
end
end | [
"def",
"expression",
"(",
"allow_assignments",
"=",
"true",
",",
"wrapped",
"=",
"true",
",",
"whitespace",
"=",
"true",
")",
"buffer",
"=",
"''",
"while",
"(",
"term",
"=",
"(",
"whitespace",
"?",
"accept",
"(",
":whitespace",
")",
":",
"nil",
")",
"||",
"modifier",
"||",
"identifier",
"||",
"method_call",
"||",
"paranthesis",
"||",
"array",
"||",
"hash",
"||",
"symbol",
"||",
"percent",
"||",
"primary_term",
")",
"buffer",
"+=",
"term",
"if",
"wrapped",
"&&",
"(",
"op",
"=",
"operation",
"||",
"(",
"allow_assignments",
"?",
"accept_stripped",
"(",
":exp_assignment",
")",
":",
"nil",
")",
")",
"buffer",
"+=",
"op",
"if",
"(",
"right_term",
"=",
"expression",
"(",
"allow_assignments",
",",
"wrapped",
")",
")",
".",
"nil?",
"Logger",
".",
"error",
":parse",
",",
"@code",
",",
"@i",
",",
"@j",
",",
":expression",
"else",
"buffer",
"+=",
"right_term",
"[",
"@value",
"]",
"end",
"elsif",
"(",
"op",
"=",
"array",
"||",
"op",
"=",
"method_call",
"||",
"op",
"=",
"ternary_operator",
"(",
"allow_assignments",
",",
"wrapped",
")",
")",
"buffer",
"+=",
"op",
"end",
"unless",
"buffer",
".",
"strip",
".",
"empty?",
"break",
"if",
"lookahead",
"(",
":exp_identifier_lookahead",
")",
".",
"nil?",
"end",
"end",
"if",
"buffer",
".",
"strip",
".",
"empty?",
"undo",
"buffer",
"else",
"[",
":expression",
",",
"buffer",
".",
"strip",
",",
"{",
"}",
"]",
"end",
"end"
] | Check if the parser matches an expression node | [
"Check",
"if",
"the",
"parser",
"matches",
"an",
"expression",
"node"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/expression.rb#L7-L51 | train |
opulent/opulent | lib/opulent/parser/expression.rb | Opulent.Parser.array_elements | def array_elements(buffer = '')
if (term = expression)
buffer += term[@value]
# If there is an array_terminator ",", recursively gather the next
# array element into the buffer
if (terminator = accept_stripped :comma)
accept_newline
buffer += array_elements terminator
end
end
# Array ended prematurely with a trailing comma, therefore the current
# parsing process will stop
error :array_elements_terminator if buffer.strip[-1] == ','
buffer
end | ruby | def array_elements(buffer = '')
if (term = expression)
buffer += term[@value]
# If there is an array_terminator ",", recursively gather the next
# array element into the buffer
if (terminator = accept_stripped :comma)
accept_newline
buffer += array_elements terminator
end
end
# Array ended prematurely with a trailing comma, therefore the current
# parsing process will stop
error :array_elements_terminator if buffer.strip[-1] == ','
buffer
end | [
"def",
"array_elements",
"(",
"buffer",
"=",
"''",
")",
"if",
"(",
"term",
"=",
"expression",
")",
"buffer",
"+=",
"term",
"[",
"@value",
"]",
"if",
"(",
"terminator",
"=",
"accept_stripped",
":comma",
")",
"accept_newline",
"buffer",
"+=",
"array_elements",
"terminator",
"end",
"end",
"error",
":array_elements_terminator",
"if",
"buffer",
".",
"strip",
"[",
"-",
"1",
"]",
"==",
"','",
"buffer",
"end"
] | Recursively gather expressions separated by a comma and add them to the
expression buffer
experssion1, experssion2, experssion3
@param buffer [String] Accumulator for the array elements | [
"Recursively",
"gather",
"expressions",
"separated",
"by",
"a",
"comma",
"and",
"add",
"them",
"to",
"the",
"expression",
"buffer"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/expression.rb#L81-L97 | train |
opulent/opulent | lib/opulent/parser/expression.rb | Opulent.Parser.method_call | def method_call
method_code = ''
while (method_start = accept(:exp_method_call))
method_code += method_start
argument = call
method_code += argument if argument
end
method_code == '' ? nil : method_code
end | ruby | def method_call
method_code = ''
while (method_start = accept(:exp_method_call))
method_code += method_start
argument = call
method_code += argument if argument
end
method_code == '' ? nil : method_code
end | [
"def",
"method_call",
"method_code",
"=",
"''",
"while",
"(",
"method_start",
"=",
"accept",
"(",
":exp_method_call",
")",
")",
"method_code",
"+=",
"method_start",
"argument",
"=",
"call",
"method_code",
"+=",
"argument",
"if",
"argument",
"end",
"method_code",
"==",
"''",
"?",
"nil",
":",
"method_code",
"end"
] | Accept a ruby method call modifier | [
"Accept",
"a",
"ruby",
"method",
"call",
"modifier"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/expression.rb#L185-L195 | train |
opulent/opulent | lib/opulent/parser/expression.rb | Opulent.Parser.call_elements | def call_elements(buffer = '')
# Accept both shorthand and default ruby hash style. Following DRY
# principles, a Proc is used to assign the value to the current key
#
# key: value
# :key => value
# value
if (symbol = accept_stripped :hash_symbol)
buffer += symbol
# Get the value associated to the current hash key
if (exp = expression(true))
buffer += exp[@value]
else
error :call_elements
end
# If there is an comma ",", recursively gather the next
# array element into the buffer
if (terminator = accept_stripped :comma)
buffer += call_elements terminator
end
elsif (exp = expression(true))
buffer += exp[@value]
if (assign = accept_stripped :hash_assignment)
buffer += assign
# Get the value associated to the current hash key
if (exp = expression(true))
buffer += exp[@value]
else
error :call_elements
end
end
# If there is an comma ",", recursively gather the next
# array element into the buffer
if (terminator = accept_stripped :comma)
buffer += call_elements terminator
end
end
buffer
end | ruby | def call_elements(buffer = '')
# Accept both shorthand and default ruby hash style. Following DRY
# principles, a Proc is used to assign the value to the current key
#
# key: value
# :key => value
# value
if (symbol = accept_stripped :hash_symbol)
buffer += symbol
# Get the value associated to the current hash key
if (exp = expression(true))
buffer += exp[@value]
else
error :call_elements
end
# If there is an comma ",", recursively gather the next
# array element into the buffer
if (terminator = accept_stripped :comma)
buffer += call_elements terminator
end
elsif (exp = expression(true))
buffer += exp[@value]
if (assign = accept_stripped :hash_assignment)
buffer += assign
# Get the value associated to the current hash key
if (exp = expression(true))
buffer += exp[@value]
else
error :call_elements
end
end
# If there is an comma ",", recursively gather the next
# array element into the buffer
if (terminator = accept_stripped :comma)
buffer += call_elements terminator
end
end
buffer
end | [
"def",
"call_elements",
"(",
"buffer",
"=",
"''",
")",
"if",
"(",
"symbol",
"=",
"accept_stripped",
":hash_symbol",
")",
"buffer",
"+=",
"symbol",
"if",
"(",
"exp",
"=",
"expression",
"(",
"true",
")",
")",
"buffer",
"+=",
"exp",
"[",
"@value",
"]",
"else",
"error",
":call_elements",
"end",
"if",
"(",
"terminator",
"=",
"accept_stripped",
":comma",
")",
"buffer",
"+=",
"call_elements",
"terminator",
"end",
"elsif",
"(",
"exp",
"=",
"expression",
"(",
"true",
")",
")",
"buffer",
"+=",
"exp",
"[",
"@value",
"]",
"if",
"(",
"assign",
"=",
"accept_stripped",
":hash_assignment",
")",
"buffer",
"+=",
"assign",
"if",
"(",
"exp",
"=",
"expression",
"(",
"true",
")",
")",
"buffer",
"+=",
"exp",
"[",
"@value",
"]",
"else",
"error",
":call_elements",
"end",
"end",
"if",
"(",
"terminator",
"=",
"accept_stripped",
":comma",
")",
"buffer",
"+=",
"call_elements",
"terminator",
"end",
"end",
"buffer",
"end"
] | Recursively gather expression attributes separated by a comma and add
them to the expression buffer
expression1, a: expression2, expression3
@param buffer [String] Accumulator for the call elements | [
"Recursively",
"gather",
"expression",
"attributes",
"separated",
"by",
"a",
"comma",
"and",
"add",
"them",
"to",
"the",
"expression",
"buffer"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/expression.rb#L218-L262 | train |
opulent/opulent | lib/opulent/parser/expression.rb | Opulent.Parser.symbol | def symbol
return unless (colon = accept :colon)
return undo colon if lookahead(:whitespace)
if (exp = expression).nil?
error :symbol
else
colon + exp[@value]
end
end | ruby | def symbol
return unless (colon = accept :colon)
return undo colon if lookahead(:whitespace)
if (exp = expression).nil?
error :symbol
else
colon + exp[@value]
end
end | [
"def",
"symbol",
"return",
"unless",
"(",
"colon",
"=",
"accept",
":colon",
")",
"return",
"undo",
"colon",
"if",
"lookahead",
"(",
":whitespace",
")",
"if",
"(",
"exp",
"=",
"expression",
")",
".",
"nil?",
"error",
":symbol",
"else",
"colon",
"+",
"exp",
"[",
"@value",
"]",
"end",
"end"
] | Accept a ruby symbol defined through a colon and a trailing expression
:'symbol'
:symbol | [
"Accept",
"a",
"ruby",
"symbol",
"defined",
"through",
"a",
"colon",
"and",
"a",
"trailing",
"expression"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/expression.rb#L269-L278 | train |
opulent/opulent | lib/opulent/parser/expression.rb | Opulent.Parser.ternary_operator | def ternary_operator(allow_assignments, wrapped)
if (buffer = accept :exp_ternary)
buffer += expression(allow_assignments, wrapped)[@value]
if (else_branch = accept :exp_ternary_else)
buffer += else_branch
buffer += expression(allow_assignments, wrapped)[@value]
end
return buffer
end
end | ruby | def ternary_operator(allow_assignments, wrapped)
if (buffer = accept :exp_ternary)
buffer += expression(allow_assignments, wrapped)[@value]
if (else_branch = accept :exp_ternary_else)
buffer += else_branch
buffer += expression(allow_assignments, wrapped)[@value]
end
return buffer
end
end | [
"def",
"ternary_operator",
"(",
"allow_assignments",
",",
"wrapped",
")",
"if",
"(",
"buffer",
"=",
"accept",
":exp_ternary",
")",
"buffer",
"+=",
"expression",
"(",
"allow_assignments",
",",
"wrapped",
")",
"[",
"@value",
"]",
"if",
"(",
"else_branch",
"=",
"accept",
":exp_ternary_else",
")",
"buffer",
"+=",
"else_branch",
"buffer",
"+=",
"expression",
"(",
"allow_assignments",
",",
"wrapped",
")",
"[",
"@value",
"]",
"end",
"return",
"buffer",
"end",
"end"
] | Accept ternary operator syntax
condition ? expression1 : expression2 | [
"Accept",
"ternary",
"operator",
"syntax"
] | 7b219bd4f54b404e8f43955b8e70925a01814b59 | https://github.com/opulent/opulent/blob/7b219bd4f54b404e8f43955b8e70925a01814b59/lib/opulent/parser/expression.rb#L344-L353 | train |
kjvarga/ajax | lib/ajax/action_controller.rb | Ajax.ActionController.serialize_ajax_info | def serialize_ajax_info
layout_name =
if Ajax.app.rails?(3)
if @_rendered_layout.is_a?(String)
@_rendered_layout =~ /.*\/([^\/]*)/ ? $1 : @_rendered_layout
elsif @_rendered_layout
@_rendered_layout.variable_name
end
else
active_layout
end
Ajax.set_header(response, :layout, layout_name)
Ajax.set_header(response, :controller, self.class.controller_name)
end | ruby | def serialize_ajax_info
layout_name =
if Ajax.app.rails?(3)
if @_rendered_layout.is_a?(String)
@_rendered_layout =~ /.*\/([^\/]*)/ ? $1 : @_rendered_layout
elsif @_rendered_layout
@_rendered_layout.variable_name
end
else
active_layout
end
Ajax.set_header(response, :layout, layout_name)
Ajax.set_header(response, :controller, self.class.controller_name)
end | [
"def",
"serialize_ajax_info",
"layout_name",
"=",
"if",
"Ajax",
".",
"app",
".",
"rails?",
"(",
"3",
")",
"if",
"@_rendered_layout",
".",
"is_a?",
"(",
"String",
")",
"@_rendered_layout",
"=~",
"/",
"\\/",
"\\/",
"/",
"?",
"$1",
":",
"@_rendered_layout",
"elsif",
"@_rendered_layout",
"@_rendered_layout",
".",
"variable_name",
"end",
"else",
"active_layout",
"end",
"Ajax",
".",
"set_header",
"(",
"response",
",",
":layout",
",",
"layout_name",
")",
"Ajax",
".",
"set_header",
"(",
"response",
",",
":controller",
",",
"self",
".",
"class",
".",
"controller_name",
")",
"end"
] | Convert the Ajax-Info hash to JSON before the request is sent.
Invoked as an after filter.
Adds the current +layout+ and +controller+ to the hash.
These values will be sent in future requests using the Ajax-Info header.
+controller+ is the result of calling ActionController#controller_name, so
if your controller is ApplicationController the value will be <tt>'application'</tt>.
+layout+ is the name of the layout without any path or extension. So for example if
layouts/simple.html.erb or layouts/ajax/simple.html.erb are rendered the
value of +layout+ would be <tt>'simple'</tt> in both cases. | [
"Convert",
"the",
"Ajax",
"-",
"Info",
"hash",
"to",
"JSON",
"before",
"the",
"request",
"is",
"sent",
".",
"Invoked",
"as",
"an",
"after",
"filter",
"."
] | e60acbc51855cd85b4907d509ea41fe0965ce72e | https://github.com/kjvarga/ajax/blob/e60acbc51855cd85b4907d509ea41fe0965ce72e/lib/ajax/action_controller.rb#L152-L165 | train |
kjvarga/ajax | lib/ajax/action_controller.rb | Ajax.ActionController._layout_for_ajax | def _layout_for_ajax(default) #:nodoc:
ajax_layout = self.class.read_inheritable_attribute(:ajax_layout)
ajax_layout = if ajax_layout.nil? && default.nil?
nil
elsif ajax_layout.nil? && !default.nil? # look for one with the default name in layouts/ajax
if default =~ /^layouts\/ajax\//
default
elsif !(default =~ /^ajax\//)
"ajax/#{default.sub(/layouts(\/)?/, '')}"
else
default
end
elsif ajax_layout.include?(?/) # path to specific layout
ajax_layout
else # layout name, look in ajax/
"ajax/#{ajax_layout}"
end
ajax_layout = ajax_layout =~ /\blayouts/ ? ajax_layout : "layouts/#{ajax_layout}" if ajax_layout
ajax_layout
end | ruby | def _layout_for_ajax(default) #:nodoc:
ajax_layout = self.class.read_inheritable_attribute(:ajax_layout)
ajax_layout = if ajax_layout.nil? && default.nil?
nil
elsif ajax_layout.nil? && !default.nil? # look for one with the default name in layouts/ajax
if default =~ /^layouts\/ajax\//
default
elsif !(default =~ /^ajax\//)
"ajax/#{default.sub(/layouts(\/)?/, '')}"
else
default
end
elsif ajax_layout.include?(?/) # path to specific layout
ajax_layout
else # layout name, look in ajax/
"ajax/#{ajax_layout}"
end
ajax_layout = ajax_layout =~ /\blayouts/ ? ajax_layout : "layouts/#{ajax_layout}" if ajax_layout
ajax_layout
end | [
"def",
"_layout_for_ajax",
"(",
"default",
")",
"ajax_layout",
"=",
"self",
".",
"class",
".",
"read_inheritable_attribute",
"(",
":ajax_layout",
")",
"ajax_layout",
"=",
"if",
"ajax_layout",
".",
"nil?",
"&&",
"default",
".",
"nil?",
"nil",
"elsif",
"ajax_layout",
".",
"nil?",
"&&",
"!",
"default",
".",
"nil?",
"if",
"default",
"=~",
"/",
"\\/",
"\\/",
"/",
"default",
"elsif",
"!",
"(",
"default",
"=~",
"/",
"\\/",
"/",
")",
"\"ajax/#{default.sub(/layouts(\\/)?/, '')}\"",
"else",
"default",
"end",
"elsif",
"ajax_layout",
".",
"include?",
"(",
"?/",
")",
"ajax_layout",
"else",
"\"ajax/#{ajax_layout}\"",
"end",
"ajax_layout",
"=",
"ajax_layout",
"=~",
"/",
"\\b",
"/",
"?",
"ajax_layout",
":",
"\"layouts/#{ajax_layout}\"",
"if",
"ajax_layout",
"ajax_layout",
"end"
] | Return the layout to use for an AJAX request, or nil if the default should be used.
If no ajax_layout is set, look for the default layout in <tt>layouts/ajax</tt>.
If the layout cannot be found, use the default. | [
"Return",
"the",
"layout",
"to",
"use",
"for",
"an",
"AJAX",
"request",
"or",
"nil",
"if",
"the",
"default",
"should",
"be",
"used",
"."
] | e60acbc51855cd85b4907d509ea41fe0965ce72e | https://github.com/kjvarga/ajax/blob/e60acbc51855cd85b4907d509ea41fe0965ce72e/lib/ajax/action_controller.rb#L258-L277 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.