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 |
---|---|---|---|---|---|---|---|---|---|---|---|
sup-heliotrope/sup | lib/sup/buffer.rb | Redwood.Buffer.write | def write y, x, s, opts={}
return if x >= @width || y >= @height
@w.attrset Colormap.color_for(opts[:color] || :none, opts[:highlight])
s ||= ""
maxl = @width - x # maximum display width width
# fill up the line with blanks to overwrite old screen contents
@w.mvaddstr y, x, " " * maxl unless opts[:no_fill]
@w.mvaddstr y, x, s.slice_by_display_length(maxl)
end | ruby | def write y, x, s, opts={}
return if x >= @width || y >= @height
@w.attrset Colormap.color_for(opts[:color] || :none, opts[:highlight])
s ||= ""
maxl = @width - x # maximum display width width
# fill up the line with blanks to overwrite old screen contents
@w.mvaddstr y, x, " " * maxl unless opts[:no_fill]
@w.mvaddstr y, x, s.slice_by_display_length(maxl)
end | [
"def",
"write",
"y",
",",
"x",
",",
"s",
",",
"opts",
"=",
"{",
"}",
"return",
"if",
"x",
">=",
"@width",
"||",
"y",
">=",
"@height",
"@w",
".",
"attrset",
"Colormap",
".",
"color_for",
"(",
"opts",
"[",
":color",
"]",
"||",
":none",
",",
"opts",
"[",
":highlight",
"]",
")",
"s",
"||=",
"\"\"",
"maxl",
"=",
"@width",
"-",
"x",
"# maximum display width width",
"# fill up the line with blanks to overwrite old screen contents",
"@w",
".",
"mvaddstr",
"y",
",",
"x",
",",
"\" \"",
"*",
"maxl",
"unless",
"opts",
"[",
":no_fill",
"]",
"@w",
".",
"mvaddstr",
"y",
",",
"x",
",",
"s",
".",
"slice_by_display_length",
"(",
"maxl",
")",
"end"
] | s nil means a blank line! | [
"s",
"nil",
"means",
"a",
"blank",
"line!"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/buffer.rb#L67-L78 | train |
sup-heliotrope/sup | lib/sup/buffer.rb | Redwood.BufferManager.roll_buffers | def roll_buffers
bufs = rollable_buffers
bufs.last.force_to_top = false
raise_to_front bufs.first
end | ruby | def roll_buffers
bufs = rollable_buffers
bufs.last.force_to_top = false
raise_to_front bufs.first
end | [
"def",
"roll_buffers",
"bufs",
"=",
"rollable_buffers",
"bufs",
".",
"last",
".",
"force_to_top",
"=",
"false",
"raise_to_front",
"bufs",
".",
"first",
"end"
] | we reset force_to_top when rolling buffers. this is so that the
human can actually still move buffers around, while still
programmatically being able to pop stuff up in the middle of
drawing a window without worrying about covering it up.
if we ever start calling roll_buffers programmatically, we will
have to change this. but it's not clear that we will ever actually
do that. | [
"we",
"reset",
"force_to_top",
"when",
"rolling",
"buffers",
".",
"this",
"is",
"so",
"that",
"the",
"human",
"can",
"actually",
"still",
"move",
"buffers",
"around",
"while",
"still",
"programmatically",
"being",
"able",
"to",
"pop",
"stuff",
"up",
"in",
"the",
"middle",
"of",
"drawing",
"a",
"window",
"without",
"worrying",
"about",
"covering",
"it",
"up",
"."
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/buffer.rb#L199-L203 | train |
sup-heliotrope/sup | lib/sup/buffer.rb | Redwood.BufferManager.ask_for_labels | def ask_for_labels domain, question, default_labels, forbidden_labels=[]
default_labels = default_labels - forbidden_labels - LabelManager::RESERVED_LABELS
default = default_labels.to_a.join(" ")
default += " " unless default.empty?
# here I would prefer to give more control and allow all_labels instead of
# user_defined_labels only
applyable_labels = (LabelManager.user_defined_labels - forbidden_labels).map { |l| LabelManager.string_for l }.sort_by { |s| s.downcase }
answer = ask_many_with_completions domain, question, applyable_labels, default
return unless answer
user_labels = answer.to_set_of_symbols
user_labels.each do |l|
if forbidden_labels.include?(l) || LabelManager::RESERVED_LABELS.include?(l)
BufferManager.flash "'#{l}' is a reserved label!"
return
end
end
user_labels
end | ruby | def ask_for_labels domain, question, default_labels, forbidden_labels=[]
default_labels = default_labels - forbidden_labels - LabelManager::RESERVED_LABELS
default = default_labels.to_a.join(" ")
default += " " unless default.empty?
# here I would prefer to give more control and allow all_labels instead of
# user_defined_labels only
applyable_labels = (LabelManager.user_defined_labels - forbidden_labels).map { |l| LabelManager.string_for l }.sort_by { |s| s.downcase }
answer = ask_many_with_completions domain, question, applyable_labels, default
return unless answer
user_labels = answer.to_set_of_symbols
user_labels.each do |l|
if forbidden_labels.include?(l) || LabelManager::RESERVED_LABELS.include?(l)
BufferManager.flash "'#{l}' is a reserved label!"
return
end
end
user_labels
end | [
"def",
"ask_for_labels",
"domain",
",",
"question",
",",
"default_labels",
",",
"forbidden_labels",
"=",
"[",
"]",
"default_labels",
"=",
"default_labels",
"-",
"forbidden_labels",
"-",
"LabelManager",
"::",
"RESERVED_LABELS",
"default",
"=",
"default_labels",
".",
"to_a",
".",
"join",
"(",
"\" \"",
")",
"default",
"+=",
"\" \"",
"unless",
"default",
".",
"empty?",
"# here I would prefer to give more control and allow all_labels instead of",
"# user_defined_labels only",
"applyable_labels",
"=",
"(",
"LabelManager",
".",
"user_defined_labels",
"-",
"forbidden_labels",
")",
".",
"map",
"{",
"|",
"l",
"|",
"LabelManager",
".",
"string_for",
"l",
"}",
".",
"sort_by",
"{",
"|",
"s",
"|",
"s",
".",
"downcase",
"}",
"answer",
"=",
"ask_many_with_completions",
"domain",
",",
"question",
",",
"applyable_labels",
",",
"default",
"return",
"unless",
"answer",
"user_labels",
"=",
"answer",
".",
"to_set_of_symbols",
"user_labels",
".",
"each",
"do",
"|",
"l",
"|",
"if",
"forbidden_labels",
".",
"include?",
"(",
"l",
")",
"||",
"LabelManager",
"::",
"RESERVED_LABELS",
".",
"include?",
"(",
"l",
")",
"BufferManager",
".",
"flash",
"\"'#{l}' is a reserved label!\"",
"return",
"end",
"end",
"user_labels",
"end"
] | returns an array of labels | [
"returns",
"an",
"array",
"of",
"labels"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/buffer.rb#L485-L506 | train |
sup-heliotrope/sup | lib/sup/buffer.rb | Redwood.BufferManager.ask | def ask domain, question, default=nil, &block
raise "impossible!" if @asking
raise "Question too long" if Ncurses.cols <= question.length
@asking = true
@textfields[domain] ||= TextField.new
tf = @textfields[domain]
completion_buf = nil
status, title = get_status_and_title @focus_buf
Ncurses.sync do
tf.activate Ncurses.stdscr, Ncurses.rows - 1, 0, Ncurses.cols, question, default, &block
@dirty = true # for some reason that blanks the whole fucking screen
draw_screen :sync => false, :status => status, :title => title
tf.position_cursor
Ncurses.refresh
end
while true
c = Ncurses::CharCode.get
next unless c.present? # getch timeout
break unless tf.handle_input c # process keystroke
if tf.new_completions?
kill_buffer completion_buf if completion_buf
shorts = tf.completions.map { |full, short| short }
prefix_len = shorts.shared_prefix(caseless=true).length
mode = CompletionMode.new shorts, :header => "Possible completions for \"#{tf.value}\": ", :prefix_len => prefix_len
completion_buf = spawn "<completions>", mode, :height => 10
draw_screen :skip_minibuf => true
tf.position_cursor
elsif tf.roll_completions?
completion_buf.mode.roll
draw_screen :skip_minibuf => true
tf.position_cursor
end
Ncurses.sync { Ncurses.refresh }
end
kill_buffer completion_buf if completion_buf
@dirty = true
@asking = false
Ncurses.sync do
tf.deactivate
draw_screen :sync => false, :status => status, :title => title
end
tf.value.tap { |x| x }
end | ruby | def ask domain, question, default=nil, &block
raise "impossible!" if @asking
raise "Question too long" if Ncurses.cols <= question.length
@asking = true
@textfields[domain] ||= TextField.new
tf = @textfields[domain]
completion_buf = nil
status, title = get_status_and_title @focus_buf
Ncurses.sync do
tf.activate Ncurses.stdscr, Ncurses.rows - 1, 0, Ncurses.cols, question, default, &block
@dirty = true # for some reason that blanks the whole fucking screen
draw_screen :sync => false, :status => status, :title => title
tf.position_cursor
Ncurses.refresh
end
while true
c = Ncurses::CharCode.get
next unless c.present? # getch timeout
break unless tf.handle_input c # process keystroke
if tf.new_completions?
kill_buffer completion_buf if completion_buf
shorts = tf.completions.map { |full, short| short }
prefix_len = shorts.shared_prefix(caseless=true).length
mode = CompletionMode.new shorts, :header => "Possible completions for \"#{tf.value}\": ", :prefix_len => prefix_len
completion_buf = spawn "<completions>", mode, :height => 10
draw_screen :skip_minibuf => true
tf.position_cursor
elsif tf.roll_completions?
completion_buf.mode.roll
draw_screen :skip_minibuf => true
tf.position_cursor
end
Ncurses.sync { Ncurses.refresh }
end
kill_buffer completion_buf if completion_buf
@dirty = true
@asking = false
Ncurses.sync do
tf.deactivate
draw_screen :sync => false, :status => status, :title => title
end
tf.value.tap { |x| x }
end | [
"def",
"ask",
"domain",
",",
"question",
",",
"default",
"=",
"nil",
",",
"&",
"block",
"raise",
"\"impossible!\"",
"if",
"@asking",
"raise",
"\"Question too long\"",
"if",
"Ncurses",
".",
"cols",
"<=",
"question",
".",
"length",
"@asking",
"=",
"true",
"@textfields",
"[",
"domain",
"]",
"||=",
"TextField",
".",
"new",
"tf",
"=",
"@textfields",
"[",
"domain",
"]",
"completion_buf",
"=",
"nil",
"status",
",",
"title",
"=",
"get_status_and_title",
"@focus_buf",
"Ncurses",
".",
"sync",
"do",
"tf",
".",
"activate",
"Ncurses",
".",
"stdscr",
",",
"Ncurses",
".",
"rows",
"-",
"1",
",",
"0",
",",
"Ncurses",
".",
"cols",
",",
"question",
",",
"default",
",",
"block",
"@dirty",
"=",
"true",
"# for some reason that blanks the whole fucking screen",
"draw_screen",
":sync",
"=>",
"false",
",",
":status",
"=>",
"status",
",",
":title",
"=>",
"title",
"tf",
".",
"position_cursor",
"Ncurses",
".",
"refresh",
"end",
"while",
"true",
"c",
"=",
"Ncurses",
"::",
"CharCode",
".",
"get",
"next",
"unless",
"c",
".",
"present?",
"# getch timeout",
"break",
"unless",
"tf",
".",
"handle_input",
"c",
"# process keystroke",
"if",
"tf",
".",
"new_completions?",
"kill_buffer",
"completion_buf",
"if",
"completion_buf",
"shorts",
"=",
"tf",
".",
"completions",
".",
"map",
"{",
"|",
"full",
",",
"short",
"|",
"short",
"}",
"prefix_len",
"=",
"shorts",
".",
"shared_prefix",
"(",
"caseless",
"=",
"true",
")",
".",
"length",
"mode",
"=",
"CompletionMode",
".",
"new",
"shorts",
",",
":header",
"=>",
"\"Possible completions for \\\"#{tf.value}\\\": \"",
",",
":prefix_len",
"=>",
"prefix_len",
"completion_buf",
"=",
"spawn",
"\"<completions>\"",
",",
"mode",
",",
":height",
"=>",
"10",
"draw_screen",
":skip_minibuf",
"=>",
"true",
"tf",
".",
"position_cursor",
"elsif",
"tf",
".",
"roll_completions?",
"completion_buf",
".",
"mode",
".",
"roll",
"draw_screen",
":skip_minibuf",
"=>",
"true",
"tf",
".",
"position_cursor",
"end",
"Ncurses",
".",
"sync",
"{",
"Ncurses",
".",
"refresh",
"}",
"end",
"kill_buffer",
"completion_buf",
"if",
"completion_buf",
"@dirty",
"=",
"true",
"@asking",
"=",
"false",
"Ncurses",
".",
"sync",
"do",
"tf",
".",
"deactivate",
"draw_screen",
":sync",
"=>",
"false",
",",
":status",
"=>",
"status",
",",
":title",
"=>",
"title",
"end",
"tf",
".",
"value",
".",
"tap",
"{",
"|",
"x",
"|",
"x",
"}",
"end"
] | for simplicitly, we always place the question at the very bottom of the
screen | [
"for",
"simplicitly",
"we",
"always",
"place",
"the",
"question",
"at",
"the",
"very",
"bottom",
"of",
"the",
"screen"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/buffer.rb#L534-L587 | train |
sup-heliotrope/sup | lib/sup/contact.rb | Redwood.ContactManager.drop_contact | def drop_contact person
aalias = @p2a[person]
@p2a.delete person
@e2p.delete person.email
@a2p.delete aalias if aalias
end | ruby | def drop_contact person
aalias = @p2a[person]
@p2a.delete person
@e2p.delete person.email
@a2p.delete aalias if aalias
end | [
"def",
"drop_contact",
"person",
"aalias",
"=",
"@p2a",
"[",
"person",
"]",
"@p2a",
".",
"delete",
"person",
"@e2p",
".",
"delete",
"person",
".",
"email",
"@a2p",
".",
"delete",
"aalias",
"if",
"aalias",
"end"
] | this may not actually be called anywhere, since we still keep contacts
around without aliases to override any fullname changes. | [
"this",
"may",
"not",
"actually",
"be",
"called",
"anywhere",
"since",
"we",
"still",
"keep",
"contacts",
"around",
"without",
"aliases",
"to",
"override",
"any",
"fullname",
"changes",
"."
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/contact.rb#L48-L53 | train |
sup-heliotrope/sup | lib/sup/modes/thread_view_mode.rb | Redwood.ThreadViewMode.regen_text | def regen_text
@text = []
@chunk_lines = []
@message_lines = []
@person_lines = []
prevm = nil
@thread.each do |m, depth, parent|
unless m.is_a? Message # handle nil and :fake_root
@text += chunk_to_lines m, nil, @text.length, depth, parent
next
end
l = @layout[m]
## is this still necessary?
next unless @layout[m].state # skip discarded drafts
## build the patina
text = chunk_to_lines m, l.state, @text.length, depth, parent, l.color, l.star_color
l.top = @text.length
l.bot = @text.length + text.length # updated below
l.prev = prevm
l.next = nil
l.depth = depth
# l.state we preserve
l.width = 0 # updated below
@layout[l.prev].next = m if l.prev
(0 ... text.length).each do |i|
@chunk_lines[@text.length + i] = m
@message_lines[@text.length + i] = m
lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.display_length }.sum
end
@text += text
prevm = m
if l.state != :closed
m.chunks.each do |c|
cl = @chunk_layout[c]
## set the default state for chunks
cl.state ||=
if c.expandable? && c.respond_to?(:initial_state)
c.initial_state
else
:closed
end
text = chunk_to_lines c, cl.state, @text.length, depth
(0 ... text.length).each do |i|
@chunk_lines[@text.length + i] = c
@message_lines[@text.length + i] = m
lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.display_length }.sum - (depth * @indent_spaces)
l.width = lw if lw > l.width
end
@text += text
end
@layout[m].bot = @text.length
end
end
end | ruby | def regen_text
@text = []
@chunk_lines = []
@message_lines = []
@person_lines = []
prevm = nil
@thread.each do |m, depth, parent|
unless m.is_a? Message # handle nil and :fake_root
@text += chunk_to_lines m, nil, @text.length, depth, parent
next
end
l = @layout[m]
## is this still necessary?
next unless @layout[m].state # skip discarded drafts
## build the patina
text = chunk_to_lines m, l.state, @text.length, depth, parent, l.color, l.star_color
l.top = @text.length
l.bot = @text.length + text.length # updated below
l.prev = prevm
l.next = nil
l.depth = depth
# l.state we preserve
l.width = 0 # updated below
@layout[l.prev].next = m if l.prev
(0 ... text.length).each do |i|
@chunk_lines[@text.length + i] = m
@message_lines[@text.length + i] = m
lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.display_length }.sum
end
@text += text
prevm = m
if l.state != :closed
m.chunks.each do |c|
cl = @chunk_layout[c]
## set the default state for chunks
cl.state ||=
if c.expandable? && c.respond_to?(:initial_state)
c.initial_state
else
:closed
end
text = chunk_to_lines c, cl.state, @text.length, depth
(0 ... text.length).each do |i|
@chunk_lines[@text.length + i] = c
@message_lines[@text.length + i] = m
lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.display_length }.sum - (depth * @indent_spaces)
l.width = lw if lw > l.width
end
@text += text
end
@layout[m].bot = @text.length
end
end
end | [
"def",
"regen_text",
"@text",
"=",
"[",
"]",
"@chunk_lines",
"=",
"[",
"]",
"@message_lines",
"=",
"[",
"]",
"@person_lines",
"=",
"[",
"]",
"prevm",
"=",
"nil",
"@thread",
".",
"each",
"do",
"|",
"m",
",",
"depth",
",",
"parent",
"|",
"unless",
"m",
".",
"is_a?",
"Message",
"# handle nil and :fake_root",
"@text",
"+=",
"chunk_to_lines",
"m",
",",
"nil",
",",
"@text",
".",
"length",
",",
"depth",
",",
"parent",
"next",
"end",
"l",
"=",
"@layout",
"[",
"m",
"]",
"## is this still necessary?",
"next",
"unless",
"@layout",
"[",
"m",
"]",
".",
"state",
"# skip discarded drafts",
"## build the patina",
"text",
"=",
"chunk_to_lines",
"m",
",",
"l",
".",
"state",
",",
"@text",
".",
"length",
",",
"depth",
",",
"parent",
",",
"l",
".",
"color",
",",
"l",
".",
"star_color",
"l",
".",
"top",
"=",
"@text",
".",
"length",
"l",
".",
"bot",
"=",
"@text",
".",
"length",
"+",
"text",
".",
"length",
"# updated below",
"l",
".",
"prev",
"=",
"prevm",
"l",
".",
"next",
"=",
"nil",
"l",
".",
"depth",
"=",
"depth",
"# l.state we preserve",
"l",
".",
"width",
"=",
"0",
"# updated below",
"@layout",
"[",
"l",
".",
"prev",
"]",
".",
"next",
"=",
"m",
"if",
"l",
".",
"prev",
"(",
"0",
"...",
"text",
".",
"length",
")",
".",
"each",
"do",
"|",
"i",
"|",
"@chunk_lines",
"[",
"@text",
".",
"length",
"+",
"i",
"]",
"=",
"m",
"@message_lines",
"[",
"@text",
".",
"length",
"+",
"i",
"]",
"=",
"m",
"lw",
"=",
"text",
"[",
"i",
"]",
".",
"flatten",
".",
"select",
"{",
"|",
"x",
"|",
"x",
".",
"is_a?",
"String",
"}",
".",
"map",
"{",
"|",
"x",
"|",
"x",
".",
"display_length",
"}",
".",
"sum",
"end",
"@text",
"+=",
"text",
"prevm",
"=",
"m",
"if",
"l",
".",
"state",
"!=",
":closed",
"m",
".",
"chunks",
".",
"each",
"do",
"|",
"c",
"|",
"cl",
"=",
"@chunk_layout",
"[",
"c",
"]",
"## set the default state for chunks",
"cl",
".",
"state",
"||=",
"if",
"c",
".",
"expandable?",
"&&",
"c",
".",
"respond_to?",
"(",
":initial_state",
")",
"c",
".",
"initial_state",
"else",
":closed",
"end",
"text",
"=",
"chunk_to_lines",
"c",
",",
"cl",
".",
"state",
",",
"@text",
".",
"length",
",",
"depth",
"(",
"0",
"...",
"text",
".",
"length",
")",
".",
"each",
"do",
"|",
"i",
"|",
"@chunk_lines",
"[",
"@text",
".",
"length",
"+",
"i",
"]",
"=",
"c",
"@message_lines",
"[",
"@text",
".",
"length",
"+",
"i",
"]",
"=",
"m",
"lw",
"=",
"text",
"[",
"i",
"]",
".",
"flatten",
".",
"select",
"{",
"|",
"x",
"|",
"x",
".",
"is_a?",
"String",
"}",
".",
"map",
"{",
"|",
"x",
"|",
"x",
".",
"display_length",
"}",
".",
"sum",
"-",
"(",
"depth",
"*",
"@indent_spaces",
")",
"l",
".",
"width",
"=",
"lw",
"if",
"lw",
">",
"l",
".",
"width",
"end",
"@text",
"+=",
"text",
"end",
"@layout",
"[",
"m",
"]",
".",
"bot",
"=",
"@text",
".",
"length",
"end",
"end",
"end"
] | here we generate the actual content lines. we accumulate
everything into @text, and we set @chunk_lines and
@message_lines, and we update @layout. | [
"here",
"we",
"generate",
"the",
"actual",
"content",
"lines",
".",
"we",
"accumulate",
"everything",
"into"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/modes/thread_view_mode.rb#L840-L901 | train |
sup-heliotrope/sup | lib/sup/index.rb | Redwood.Index.num_results_for | def num_results_for query={}
xapian_query = build_xapian_query query
matchset = run_query xapian_query, 0, 0, 100
matchset.matches_estimated
end | ruby | def num_results_for query={}
xapian_query = build_xapian_query query
matchset = run_query xapian_query, 0, 0, 100
matchset.matches_estimated
end | [
"def",
"num_results_for",
"query",
"=",
"{",
"}",
"xapian_query",
"=",
"build_xapian_query",
"query",
"matchset",
"=",
"run_query",
"xapian_query",
",",
"0",
",",
"0",
",",
"100",
"matchset",
".",
"matches_estimated",
"end"
] | Return the number of matches for query in the index | [
"Return",
"the",
"number",
"of",
"matches",
"for",
"query",
"in",
"the",
"index"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/index.rb#L169-L173 | train |
sup-heliotrope/sup | lib/sup/index.rb | Redwood.Index.build_message | def build_message id
entry = synchronize { get_entry id }
return unless entry
locations = entry[:locations].map do |source_id,source_info|
source = SourceManager[source_id]
raise "invalid source #{source_id}" unless source
Location.new source, source_info
end
m = Message.new :locations => locations,
:labels => entry[:labels],
:snippet => entry[:snippet]
# Try to find person from contacts before falling back to
# generating it from the address.
mk_person = lambda { |x| Person.from_name_and_email(*x.reverse!) }
entry[:from] = mk_person[entry[:from]]
entry[:to].map!(&mk_person)
entry[:cc].map!(&mk_person)
entry[:bcc].map!(&mk_person)
m.load_from_index! entry
m
end | ruby | def build_message id
entry = synchronize { get_entry id }
return unless entry
locations = entry[:locations].map do |source_id,source_info|
source = SourceManager[source_id]
raise "invalid source #{source_id}" unless source
Location.new source, source_info
end
m = Message.new :locations => locations,
:labels => entry[:labels],
:snippet => entry[:snippet]
# Try to find person from contacts before falling back to
# generating it from the address.
mk_person = lambda { |x| Person.from_name_and_email(*x.reverse!) }
entry[:from] = mk_person[entry[:from]]
entry[:to].map!(&mk_person)
entry[:cc].map!(&mk_person)
entry[:bcc].map!(&mk_person)
m.load_from_index! entry
m
end | [
"def",
"build_message",
"id",
"entry",
"=",
"synchronize",
"{",
"get_entry",
"id",
"}",
"return",
"unless",
"entry",
"locations",
"=",
"entry",
"[",
":locations",
"]",
".",
"map",
"do",
"|",
"source_id",
",",
"source_info",
"|",
"source",
"=",
"SourceManager",
"[",
"source_id",
"]",
"raise",
"\"invalid source #{source_id}\"",
"unless",
"source",
"Location",
".",
"new",
"source",
",",
"source_info",
"end",
"m",
"=",
"Message",
".",
"new",
":locations",
"=>",
"locations",
",",
":labels",
"=>",
"entry",
"[",
":labels",
"]",
",",
":snippet",
"=>",
"entry",
"[",
":snippet",
"]",
"# Try to find person from contacts before falling back to",
"# generating it from the address.",
"mk_person",
"=",
"lambda",
"{",
"|",
"x",
"|",
"Person",
".",
"from_name_and_email",
"(",
"x",
".",
"reverse!",
")",
"}",
"entry",
"[",
":from",
"]",
"=",
"mk_person",
"[",
"entry",
"[",
":from",
"]",
"]",
"entry",
"[",
":to",
"]",
".",
"map!",
"(",
"mk_person",
")",
"entry",
"[",
":cc",
"]",
".",
"map!",
"(",
"mk_person",
")",
"entry",
"[",
":bcc",
"]",
".",
"map!",
"(",
"mk_person",
")",
"m",
".",
"load_from_index!",
"entry",
"m",
"end"
] | Load message with the given message-id from the index | [
"Load",
"message",
"with",
"the",
"given",
"message",
"-",
"id",
"from",
"the",
"index"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/index.rb#L235-L259 | train |
sup-heliotrope/sup | lib/sup/index.rb | Redwood.Index.load_contacts | def load_contacts email_addresses, opts={}
contacts = Set.new
num = opts[:num] || 20
each_id_by_date :participants => email_addresses do |id,b|
break if contacts.size >= num
m = b.call
([m.from]+m.to+m.cc+m.bcc).compact.each { |p| contacts << [p.name, p.email] }
end
contacts.to_a.compact[0...num].map { |n,e| Person.from_name_and_email n, e }
end | ruby | def load_contacts email_addresses, opts={}
contacts = Set.new
num = opts[:num] || 20
each_id_by_date :participants => email_addresses do |id,b|
break if contacts.size >= num
m = b.call
([m.from]+m.to+m.cc+m.bcc).compact.each { |p| contacts << [p.name, p.email] }
end
contacts.to_a.compact[0...num].map { |n,e| Person.from_name_and_email n, e }
end | [
"def",
"load_contacts",
"email_addresses",
",",
"opts",
"=",
"{",
"}",
"contacts",
"=",
"Set",
".",
"new",
"num",
"=",
"opts",
"[",
":num",
"]",
"||",
"20",
"each_id_by_date",
":participants",
"=>",
"email_addresses",
"do",
"|",
"id",
",",
"b",
"|",
"break",
"if",
"contacts",
".",
"size",
">=",
"num",
"m",
"=",
"b",
".",
"call",
"(",
"[",
"m",
".",
"from",
"]",
"+",
"m",
".",
"to",
"+",
"m",
".",
"cc",
"+",
"m",
".",
"bcc",
")",
".",
"compact",
".",
"each",
"{",
"|",
"p",
"|",
"contacts",
"<<",
"[",
"p",
".",
"name",
",",
"p",
".",
"email",
"]",
"}",
"end",
"contacts",
".",
"to_a",
".",
"compact",
"[",
"0",
"...",
"num",
"]",
".",
"map",
"{",
"|",
"n",
",",
"e",
"|",
"Person",
".",
"from_name_and_email",
"n",
",",
"e",
"}",
"end"
] | Given an array of email addresses, return an array of Person objects that
have sent mail to or received mail from any of the given addresses. | [
"Given",
"an",
"array",
"of",
"email",
"addresses",
"return",
"an",
"array",
"of",
"Person",
"objects",
"that",
"have",
"sent",
"mail",
"to",
"or",
"received",
"mail",
"from",
"any",
"of",
"the",
"given",
"addresses",
"."
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/index.rb#L268-L277 | train |
sup-heliotrope/sup | lib/sup/index.rb | Redwood.Index.index_message_static | def index_message_static m, doc, entry
# Person names are indexed with several prefixes
person_termer = lambda do |d|
lambda do |p|
doc.index_text p.name, PREFIX["#{d}_name"][:prefix] if p.name
doc.index_text p.email, PREFIX['email_text'][:prefix]
doc.add_term mkterm(:email, d, p.email)
end
end
person_termer[:from][m.from] if m.from
(m.to+m.cc+m.bcc).each(&(person_termer[:to]))
# Full text search content
subject_text = m.indexable_subject
body_text = m.indexable_body
doc.index_text subject_text, PREFIX['subject'][:prefix]
doc.index_text body_text, PREFIX['body'][:prefix]
m.attachments.each { |a| doc.index_text a, PREFIX['attachment'][:prefix] }
# Miscellaneous terms
doc.add_term mkterm(:date, m.date) if m.date
doc.add_term mkterm(:type, 'mail')
doc.add_term mkterm(:msgid, m.id)
m.attachments.each do |a|
a =~ /\.(\w+)$/ or next
doc.add_term mkterm(:attachment_extension, $1)
end
# Date value for range queries
date_value = begin
Xapian.sortable_serialise m.date.to_i
rescue TypeError
Xapian.sortable_serialise 0
end
doc.add_value MSGID_VALUENO, m.id
doc.add_value DATE_VALUENO, date_value
end | ruby | def index_message_static m, doc, entry
# Person names are indexed with several prefixes
person_termer = lambda do |d|
lambda do |p|
doc.index_text p.name, PREFIX["#{d}_name"][:prefix] if p.name
doc.index_text p.email, PREFIX['email_text'][:prefix]
doc.add_term mkterm(:email, d, p.email)
end
end
person_termer[:from][m.from] if m.from
(m.to+m.cc+m.bcc).each(&(person_termer[:to]))
# Full text search content
subject_text = m.indexable_subject
body_text = m.indexable_body
doc.index_text subject_text, PREFIX['subject'][:prefix]
doc.index_text body_text, PREFIX['body'][:prefix]
m.attachments.each { |a| doc.index_text a, PREFIX['attachment'][:prefix] }
# Miscellaneous terms
doc.add_term mkterm(:date, m.date) if m.date
doc.add_term mkterm(:type, 'mail')
doc.add_term mkterm(:msgid, m.id)
m.attachments.each do |a|
a =~ /\.(\w+)$/ or next
doc.add_term mkterm(:attachment_extension, $1)
end
# Date value for range queries
date_value = begin
Xapian.sortable_serialise m.date.to_i
rescue TypeError
Xapian.sortable_serialise 0
end
doc.add_value MSGID_VALUENO, m.id
doc.add_value DATE_VALUENO, date_value
end | [
"def",
"index_message_static",
"m",
",",
"doc",
",",
"entry",
"# Person names are indexed with several prefixes",
"person_termer",
"=",
"lambda",
"do",
"|",
"d",
"|",
"lambda",
"do",
"|",
"p",
"|",
"doc",
".",
"index_text",
"p",
".",
"name",
",",
"PREFIX",
"[",
"\"#{d}_name\"",
"]",
"[",
":prefix",
"]",
"if",
"p",
".",
"name",
"doc",
".",
"index_text",
"p",
".",
"email",
",",
"PREFIX",
"[",
"'email_text'",
"]",
"[",
":prefix",
"]",
"doc",
".",
"add_term",
"mkterm",
"(",
":email",
",",
"d",
",",
"p",
".",
"email",
")",
"end",
"end",
"person_termer",
"[",
":from",
"]",
"[",
"m",
".",
"from",
"]",
"if",
"m",
".",
"from",
"(",
"m",
".",
"to",
"+",
"m",
".",
"cc",
"+",
"m",
".",
"bcc",
")",
".",
"each",
"(",
"(",
"person_termer",
"[",
":to",
"]",
")",
")",
"# Full text search content",
"subject_text",
"=",
"m",
".",
"indexable_subject",
"body_text",
"=",
"m",
".",
"indexable_body",
"doc",
".",
"index_text",
"subject_text",
",",
"PREFIX",
"[",
"'subject'",
"]",
"[",
":prefix",
"]",
"doc",
".",
"index_text",
"body_text",
",",
"PREFIX",
"[",
"'body'",
"]",
"[",
":prefix",
"]",
"m",
".",
"attachments",
".",
"each",
"{",
"|",
"a",
"|",
"doc",
".",
"index_text",
"a",
",",
"PREFIX",
"[",
"'attachment'",
"]",
"[",
":prefix",
"]",
"}",
"# Miscellaneous terms",
"doc",
".",
"add_term",
"mkterm",
"(",
":date",
",",
"m",
".",
"date",
")",
"if",
"m",
".",
"date",
"doc",
".",
"add_term",
"mkterm",
"(",
":type",
",",
"'mail'",
")",
"doc",
".",
"add_term",
"mkterm",
"(",
":msgid",
",",
"m",
".",
"id",
")",
"m",
".",
"attachments",
".",
"each",
"do",
"|",
"a",
"|",
"a",
"=~",
"/",
"\\.",
"\\w",
"/",
"or",
"next",
"doc",
".",
"add_term",
"mkterm",
"(",
":attachment_extension",
",",
"$1",
")",
"end",
"# Date value for range queries",
"date_value",
"=",
"begin",
"Xapian",
".",
"sortable_serialise",
"m",
".",
"date",
".",
"to_i",
"rescue",
"TypeError",
"Xapian",
".",
"sortable_serialise",
"0",
"end",
"doc",
".",
"add_value",
"MSGID_VALUENO",
",",
"m",
".",
"id",
"doc",
".",
"add_value",
"DATE_VALUENO",
",",
"date_value",
"end"
] | Index content that can't be changed by the user | [
"Index",
"content",
"that",
"can",
"t",
"be",
"changed",
"by",
"the",
"user"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/index.rb#L748-L786 | train |
sup-heliotrope/sup | lib/sup/index.rb | Redwood.Index.mkterm | def mkterm type, *args
case type
when :label
PREFIX['label'][:prefix] + args[0].to_s.downcase
when :type
PREFIX['type'][:prefix] + args[0].to_s.downcase
when :date
PREFIX['date'][:prefix] + args[0].getutc.strftime("%Y%m%d%H%M%S")
when :email
case args[0]
when :from then PREFIX['from_email'][:prefix]
when :to then PREFIX['to_email'][:prefix]
else raise "Invalid email term type #{args[0]}"
end + args[1].to_s.downcase
when :source_id
PREFIX['source_id'][:prefix] + args[0].to_s.downcase
when :location
PREFIX['location'][:prefix] + [args[0]].pack('n') + args[1].to_s
when :attachment_extension
PREFIX['attachment_extension'][:prefix] + args[0].to_s.downcase
when :msgid, :ref, :thread
PREFIX[type.to_s][:prefix] + args[0][0...(MAX_TERM_LENGTH-1)]
else
raise "Invalid term type #{type}"
end
end | ruby | def mkterm type, *args
case type
when :label
PREFIX['label'][:prefix] + args[0].to_s.downcase
when :type
PREFIX['type'][:prefix] + args[0].to_s.downcase
when :date
PREFIX['date'][:prefix] + args[0].getutc.strftime("%Y%m%d%H%M%S")
when :email
case args[0]
when :from then PREFIX['from_email'][:prefix]
when :to then PREFIX['to_email'][:prefix]
else raise "Invalid email term type #{args[0]}"
end + args[1].to_s.downcase
when :source_id
PREFIX['source_id'][:prefix] + args[0].to_s.downcase
when :location
PREFIX['location'][:prefix] + [args[0]].pack('n') + args[1].to_s
when :attachment_extension
PREFIX['attachment_extension'][:prefix] + args[0].to_s.downcase
when :msgid, :ref, :thread
PREFIX[type.to_s][:prefix] + args[0][0...(MAX_TERM_LENGTH-1)]
else
raise "Invalid term type #{type}"
end
end | [
"def",
"mkterm",
"type",
",",
"*",
"args",
"case",
"type",
"when",
":label",
"PREFIX",
"[",
"'label'",
"]",
"[",
":prefix",
"]",
"+",
"args",
"[",
"0",
"]",
".",
"to_s",
".",
"downcase",
"when",
":type",
"PREFIX",
"[",
"'type'",
"]",
"[",
":prefix",
"]",
"+",
"args",
"[",
"0",
"]",
".",
"to_s",
".",
"downcase",
"when",
":date",
"PREFIX",
"[",
"'date'",
"]",
"[",
":prefix",
"]",
"+",
"args",
"[",
"0",
"]",
".",
"getutc",
".",
"strftime",
"(",
"\"%Y%m%d%H%M%S\"",
")",
"when",
":email",
"case",
"args",
"[",
"0",
"]",
"when",
":from",
"then",
"PREFIX",
"[",
"'from_email'",
"]",
"[",
":prefix",
"]",
"when",
":to",
"then",
"PREFIX",
"[",
"'to_email'",
"]",
"[",
":prefix",
"]",
"else",
"raise",
"\"Invalid email term type #{args[0]}\"",
"end",
"+",
"args",
"[",
"1",
"]",
".",
"to_s",
".",
"downcase",
"when",
":source_id",
"PREFIX",
"[",
"'source_id'",
"]",
"[",
":prefix",
"]",
"+",
"args",
"[",
"0",
"]",
".",
"to_s",
".",
"downcase",
"when",
":location",
"PREFIX",
"[",
"'location'",
"]",
"[",
":prefix",
"]",
"+",
"[",
"args",
"[",
"0",
"]",
"]",
".",
"pack",
"(",
"'n'",
")",
"+",
"args",
"[",
"1",
"]",
".",
"to_s",
"when",
":attachment_extension",
"PREFIX",
"[",
"'attachment_extension'",
"]",
"[",
":prefix",
"]",
"+",
"args",
"[",
"0",
"]",
".",
"to_s",
".",
"downcase",
"when",
":msgid",
",",
":ref",
",",
":thread",
"PREFIX",
"[",
"type",
".",
"to_s",
"]",
"[",
":prefix",
"]",
"+",
"args",
"[",
"0",
"]",
"[",
"0",
"...",
"(",
"MAX_TERM_LENGTH",
"-",
"1",
")",
"]",
"else",
"raise",
"\"Invalid term type #{type}\"",
"end",
"end"
] | Construct a Xapian term | [
"Construct",
"a",
"Xapian",
"term"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/index.rb#L841-L866 | train |
sup-heliotrope/sup | lib/sup/thread.rb | Redwood.ThreadSet.link | def link p, c, overwrite=false
if p == c || p.descendant_of?(c) || c.descendant_of?(p) # would create a loop
#puts "*** linking parent #{p.id} and child #{c.id} would create a loop"
return
end
#puts "in link for #{p.id} to #{c.id}, perform? #{c.parent.nil?} || #{overwrite}"
return unless c.parent.nil? || overwrite
remove_container c
p.children << c
c.parent = p
## if the child was previously a top-level container, it now ain't,
## so ditch our thread and kill it if necessary
prune_thread_of c
end | ruby | def link p, c, overwrite=false
if p == c || p.descendant_of?(c) || c.descendant_of?(p) # would create a loop
#puts "*** linking parent #{p.id} and child #{c.id} would create a loop"
return
end
#puts "in link for #{p.id} to #{c.id}, perform? #{c.parent.nil?} || #{overwrite}"
return unless c.parent.nil? || overwrite
remove_container c
p.children << c
c.parent = p
## if the child was previously a top-level container, it now ain't,
## so ditch our thread and kill it if necessary
prune_thread_of c
end | [
"def",
"link",
"p",
",",
"c",
",",
"overwrite",
"=",
"false",
"if",
"p",
"==",
"c",
"||",
"p",
".",
"descendant_of?",
"(",
"c",
")",
"||",
"c",
".",
"descendant_of?",
"(",
"p",
")",
"# would create a loop",
"#puts \"*** linking parent #{p.id} and child #{c.id} would create a loop\"",
"return",
"end",
"#puts \"in link for #{p.id} to #{c.id}, perform? #{c.parent.nil?} || #{overwrite}\"",
"return",
"unless",
"c",
".",
"parent",
".",
"nil?",
"||",
"overwrite",
"remove_container",
"c",
"p",
".",
"children",
"<<",
"c",
"c",
".",
"parent",
"=",
"p",
"## if the child was previously a top-level container, it now ain't,",
"## so ditch our thread and kill it if necessary",
"prune_thread_of",
"c",
"end"
] | link two containers | [
"link",
"two",
"containers"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/thread.rb#L292-L308 | train |
sup-heliotrope/sup | lib/sup/thread.rb | Redwood.ThreadSet.load_thread_for_message | def load_thread_for_message m, opts={}
good = @index.each_message_in_thread_for m, opts do |mid, builder|
next if contains_id? mid
add_message builder.call
end
add_message m if good
end | ruby | def load_thread_for_message m, opts={}
good = @index.each_message_in_thread_for m, opts do |mid, builder|
next if contains_id? mid
add_message builder.call
end
add_message m if good
end | [
"def",
"load_thread_for_message",
"m",
",",
"opts",
"=",
"{",
"}",
"good",
"=",
"@index",
".",
"each_message_in_thread_for",
"m",
",",
"opts",
"do",
"|",
"mid",
",",
"builder",
"|",
"next",
"if",
"contains_id?",
"mid",
"add_message",
"builder",
".",
"call",
"end",
"add_message",
"m",
"if",
"good",
"end"
] | loads in all messages needed to thread m
may do nothing if m's thread is killed | [
"loads",
"in",
"all",
"messages",
"needed",
"to",
"thread",
"m",
"may",
"do",
"nothing",
"if",
"m",
"s",
"thread",
"is",
"killed"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/thread.rb#L352-L358 | train |
sup-heliotrope/sup | lib/sup/thread.rb | Redwood.ThreadSet.add_thread | def add_thread t
raise "duplicate" if @threads.values.member? t
t.each { |m, *o| add_message m }
end | ruby | def add_thread t
raise "duplicate" if @threads.values.member? t
t.each { |m, *o| add_message m }
end | [
"def",
"add_thread",
"t",
"raise",
"\"duplicate\"",
"if",
"@threads",
".",
"values",
".",
"member?",
"t",
"t",
".",
"each",
"{",
"|",
"m",
",",
"*",
"o",
"|",
"add_message",
"m",
"}",
"end"
] | merges in a pre-loaded thread | [
"merges",
"in",
"a",
"pre",
"-",
"loaded",
"thread"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/thread.rb#L361-L364 | train |
sup-heliotrope/sup | lib/sup/thread.rb | Redwood.ThreadSet.join_threads | def join_threads threads
return if threads.size < 2
containers = threads.map do |t|
c = @messages.member?(t.first.id) ? @messages[t.first.id] : nil
raise "not in threadset: #{t.first.id}" unless c && c.message
c
end
## use subject headers heuristically
parent = containers.find { |c| !c.is_reply? }
## no thread was rooted by a non-reply, so make a fake parent
parent ||= @messages["joining-ref-" + containers.map { |c| c.id }.join("-")]
containers.each do |c|
next if c == parent
c.message.add_ref parent.id
link parent, c
end
true
end | ruby | def join_threads threads
return if threads.size < 2
containers = threads.map do |t|
c = @messages.member?(t.first.id) ? @messages[t.first.id] : nil
raise "not in threadset: #{t.first.id}" unless c && c.message
c
end
## use subject headers heuristically
parent = containers.find { |c| !c.is_reply? }
## no thread was rooted by a non-reply, so make a fake parent
parent ||= @messages["joining-ref-" + containers.map { |c| c.id }.join("-")]
containers.each do |c|
next if c == parent
c.message.add_ref parent.id
link parent, c
end
true
end | [
"def",
"join_threads",
"threads",
"return",
"if",
"threads",
".",
"size",
"<",
"2",
"containers",
"=",
"threads",
".",
"map",
"do",
"|",
"t",
"|",
"c",
"=",
"@messages",
".",
"member?",
"(",
"t",
".",
"first",
".",
"id",
")",
"?",
"@messages",
"[",
"t",
".",
"first",
".",
"id",
"]",
":",
"nil",
"raise",
"\"not in threadset: #{t.first.id}\"",
"unless",
"c",
"&&",
"c",
".",
"message",
"c",
"end",
"## use subject headers heuristically",
"parent",
"=",
"containers",
".",
"find",
"{",
"|",
"c",
"|",
"!",
"c",
".",
"is_reply?",
"}",
"## no thread was rooted by a non-reply, so make a fake parent",
"parent",
"||=",
"@messages",
"[",
"\"joining-ref-\"",
"+",
"containers",
".",
"map",
"{",
"|",
"c",
"|",
"c",
".",
"id",
"}",
".",
"join",
"(",
"\"-\"",
")",
"]",
"containers",
".",
"each",
"do",
"|",
"c",
"|",
"next",
"if",
"c",
"==",
"parent",
"c",
".",
"message",
".",
"add_ref",
"parent",
".",
"id",
"link",
"parent",
",",
"c",
"end",
"true",
"end"
] | merges two threads together. both must be members of this threadset.
does its best, heuristically, to determine which is the parent. | [
"merges",
"two",
"threads",
"together",
".",
"both",
"must",
"be",
"members",
"of",
"this",
"threadset",
".",
"does",
"its",
"best",
"heuristically",
"to",
"determine",
"which",
"is",
"the",
"parent",
"."
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/thread.rb#L368-L390 | train |
sup-heliotrope/sup | lib/sup/thread.rb | Redwood.ThreadSet.add_message | def add_message message
el = @messages[message.id]
return if el.message # we've seen it before
#puts "adding: #{message.id}, refs #{message.refs.inspect}"
el.message = message
oldroot = el.root
## link via references:
(message.refs + [el.id]).inject(nil) do |prev, ref_id|
ref = @messages[ref_id]
link prev, ref if prev
ref
end
## link via in-reply-to:
message.replytos.each do |ref_id|
ref = @messages[ref_id]
link ref, el, true
break # only do the first one
end
root = el.root
key =
if thread_by_subj?
Message.normalize_subj root.subj
else
root.id
end
## check to see if the subject is still the same (in the case
## that we first added a child message with a different
## subject)
if root.thread
if @threads.member?(key) && @threads[key] != root.thread
@threads.delete key
end
else
thread = @threads[key]
thread << root
root.thread = thread
end
## last bit
@num_messages += 1
end | ruby | def add_message message
el = @messages[message.id]
return if el.message # we've seen it before
#puts "adding: #{message.id}, refs #{message.refs.inspect}"
el.message = message
oldroot = el.root
## link via references:
(message.refs + [el.id]).inject(nil) do |prev, ref_id|
ref = @messages[ref_id]
link prev, ref if prev
ref
end
## link via in-reply-to:
message.replytos.each do |ref_id|
ref = @messages[ref_id]
link ref, el, true
break # only do the first one
end
root = el.root
key =
if thread_by_subj?
Message.normalize_subj root.subj
else
root.id
end
## check to see if the subject is still the same (in the case
## that we first added a child message with a different
## subject)
if root.thread
if @threads.member?(key) && @threads[key] != root.thread
@threads.delete key
end
else
thread = @threads[key]
thread << root
root.thread = thread
end
## last bit
@num_messages += 1
end | [
"def",
"add_message",
"message",
"el",
"=",
"@messages",
"[",
"message",
".",
"id",
"]",
"return",
"if",
"el",
".",
"message",
"# we've seen it before",
"#puts \"adding: #{message.id}, refs #{message.refs.inspect}\"",
"el",
".",
"message",
"=",
"message",
"oldroot",
"=",
"el",
".",
"root",
"## link via references:",
"(",
"message",
".",
"refs",
"+",
"[",
"el",
".",
"id",
"]",
")",
".",
"inject",
"(",
"nil",
")",
"do",
"|",
"prev",
",",
"ref_id",
"|",
"ref",
"=",
"@messages",
"[",
"ref_id",
"]",
"link",
"prev",
",",
"ref",
"if",
"prev",
"ref",
"end",
"## link via in-reply-to:",
"message",
".",
"replytos",
".",
"each",
"do",
"|",
"ref_id",
"|",
"ref",
"=",
"@messages",
"[",
"ref_id",
"]",
"link",
"ref",
",",
"el",
",",
"true",
"break",
"# only do the first one",
"end",
"root",
"=",
"el",
".",
"root",
"key",
"=",
"if",
"thread_by_subj?",
"Message",
".",
"normalize_subj",
"root",
".",
"subj",
"else",
"root",
".",
"id",
"end",
"## check to see if the subject is still the same (in the case",
"## that we first added a child message with a different",
"## subject)",
"if",
"root",
".",
"thread",
"if",
"@threads",
".",
"member?",
"(",
"key",
")",
"&&",
"@threads",
"[",
"key",
"]",
"!=",
"root",
".",
"thread",
"@threads",
".",
"delete",
"key",
"end",
"else",
"thread",
"=",
"@threads",
"[",
"key",
"]",
"thread",
"<<",
"root",
"root",
".",
"thread",
"=",
"thread",
"end",
"## last bit",
"@num_messages",
"+=",
"1",
"end"
] | the heart of the threading code | [
"the",
"heart",
"of",
"the",
"threading",
"code"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/thread.rb#L403-L449 | train |
sup-heliotrope/sup | lib/sup/message.rb | Redwood.Message.load_from_source! | def load_from_source!
@chunks ||=
begin
## we need to re-read the header because it contains information
## that we don't store in the index. actually i think it's just
## the mailing list address (if any), so this is kinda overkill.
## i could just store that in the index, but i think there might
## be other things like that in the future, and i'd rather not
## bloat the index.
## actually, it's also the differentiation between to/cc/bcc,
## so i will keep this.
rmsg = location.parsed_message
parse_header rmsg.header
message_to_chunks rmsg
rescue SourceError, SocketError, RMail::EncodingUnsupportedError => e
warn_with_location "problem reading message #{id}"
debug "could not load message: #{location.inspect}, exception: #{e.inspect}"
[Chunk::Text.new(error_message.split("\n"))]
rescue Exception => e
warn_with_location "problem reading message #{id}"
debug "could not load message: #{location.inspect}, exception: #{e.inspect}"
raise e
end
end | ruby | def load_from_source!
@chunks ||=
begin
## we need to re-read the header because it contains information
## that we don't store in the index. actually i think it's just
## the mailing list address (if any), so this is kinda overkill.
## i could just store that in the index, but i think there might
## be other things like that in the future, and i'd rather not
## bloat the index.
## actually, it's also the differentiation between to/cc/bcc,
## so i will keep this.
rmsg = location.parsed_message
parse_header rmsg.header
message_to_chunks rmsg
rescue SourceError, SocketError, RMail::EncodingUnsupportedError => e
warn_with_location "problem reading message #{id}"
debug "could not load message: #{location.inspect}, exception: #{e.inspect}"
[Chunk::Text.new(error_message.split("\n"))]
rescue Exception => e
warn_with_location "problem reading message #{id}"
debug "could not load message: #{location.inspect}, exception: #{e.inspect}"
raise e
end
end | [
"def",
"load_from_source!",
"@chunks",
"||=",
"begin",
"## we need to re-read the header because it contains information",
"## that we don't store in the index. actually i think it's just",
"## the mailing list address (if any), so this is kinda overkill.",
"## i could just store that in the index, but i think there might",
"## be other things like that in the future, and i'd rather not",
"## bloat the index.",
"## actually, it's also the differentiation between to/cc/bcc,",
"## so i will keep this.",
"rmsg",
"=",
"location",
".",
"parsed_message",
"parse_header",
"rmsg",
".",
"header",
"message_to_chunks",
"rmsg",
"rescue",
"SourceError",
",",
"SocketError",
",",
"RMail",
"::",
"EncodingUnsupportedError",
"=>",
"e",
"warn_with_location",
"\"problem reading message #{id}\"",
"debug",
"\"could not load message: #{location.inspect}, exception: #{e.inspect}\"",
"[",
"Chunk",
"::",
"Text",
".",
"new",
"(",
"error_message",
".",
"split",
"(",
"\"\\n\"",
")",
")",
"]",
"rescue",
"Exception",
"=>",
"e",
"warn_with_location",
"\"problem reading message #{id}\"",
"debug",
"\"could not load message: #{location.inspect}, exception: #{e.inspect}\"",
"raise",
"e",
"end",
"end"
] | this is called when the message body needs to actually be loaded. | [
"this",
"is",
"called",
"when",
"the",
"message",
"body",
"needs",
"to",
"actually",
"be",
"loaded",
"."
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/message.rb#L252-L280 | train |
sup-heliotrope/sup | lib/sup/message.rb | Redwood.Message.indexable_content | def indexable_content
load_from_source!
[
from && from.indexable_content,
to.map { |p| p.indexable_content },
cc.map { |p| p.indexable_content },
bcc.map { |p| p.indexable_content },
indexable_chunks.map { |c| c.lines.map { |l| l.fix_encoding! } },
indexable_subject,
].flatten.compact.join " "
end | ruby | def indexable_content
load_from_source!
[
from && from.indexable_content,
to.map { |p| p.indexable_content },
cc.map { |p| p.indexable_content },
bcc.map { |p| p.indexable_content },
indexable_chunks.map { |c| c.lines.map { |l| l.fix_encoding! } },
indexable_subject,
].flatten.compact.join " "
end | [
"def",
"indexable_content",
"load_from_source!",
"[",
"from",
"&&",
"from",
".",
"indexable_content",
",",
"to",
".",
"map",
"{",
"|",
"p",
"|",
"p",
".",
"indexable_content",
"}",
",",
"cc",
".",
"map",
"{",
"|",
"p",
"|",
"p",
".",
"indexable_content",
"}",
",",
"bcc",
".",
"map",
"{",
"|",
"p",
"|",
"p",
".",
"indexable_content",
"}",
",",
"indexable_chunks",
".",
"map",
"{",
"|",
"c",
"|",
"c",
".",
"lines",
".",
"map",
"{",
"|",
"l",
"|",
"l",
".",
"fix_encoding!",
"}",
"}",
",",
"indexable_subject",
",",
"]",
".",
"flatten",
".",
"compact",
".",
"join",
"\" \"",
"end"
] | returns all the content from a message that will be indexed | [
"returns",
"all",
"the",
"content",
"from",
"a",
"message",
"that",
"will",
"be",
"indexed"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/message.rb#L337-L347 | train |
sup-heliotrope/sup | lib/sup/message.rb | Redwood.Message.multipart_signed_to_chunks | def multipart_signed_to_chunks m
if m.body.size != 2
warn_with_location "multipart/signed with #{m.body.size} parts (expecting 2)"
return
end
payload, signature = m.body
if signature.multipart?
warn_with_location "multipart/signed with payload multipart #{payload.multipart?} and signature multipart #{signature.multipart?}"
return
end
## this probably will never happen
if payload.header.content_type && payload.header.content_type.downcase == "application/pgp-signature"
warn_with_location "multipart/signed with payload content type #{payload.header.content_type}"
return
end
if signature.header.content_type && signature.header.content_type.downcase != "application/pgp-signature"
## unknown signature type; just ignore.
#warn "multipart/signed with signature content type #{signature.header.content_type}"
return
end
[CryptoManager.verify(payload, signature), message_to_chunks(payload)].flatten.compact
end | ruby | def multipart_signed_to_chunks m
if m.body.size != 2
warn_with_location "multipart/signed with #{m.body.size} parts (expecting 2)"
return
end
payload, signature = m.body
if signature.multipart?
warn_with_location "multipart/signed with payload multipart #{payload.multipart?} and signature multipart #{signature.multipart?}"
return
end
## this probably will never happen
if payload.header.content_type && payload.header.content_type.downcase == "application/pgp-signature"
warn_with_location "multipart/signed with payload content type #{payload.header.content_type}"
return
end
if signature.header.content_type && signature.header.content_type.downcase != "application/pgp-signature"
## unknown signature type; just ignore.
#warn "multipart/signed with signature content type #{signature.header.content_type}"
return
end
[CryptoManager.verify(payload, signature), message_to_chunks(payload)].flatten.compact
end | [
"def",
"multipart_signed_to_chunks",
"m",
"if",
"m",
".",
"body",
".",
"size",
"!=",
"2",
"warn_with_location",
"\"multipart/signed with #{m.body.size} parts (expecting 2)\"",
"return",
"end",
"payload",
",",
"signature",
"=",
"m",
".",
"body",
"if",
"signature",
".",
"multipart?",
"warn_with_location",
"\"multipart/signed with payload multipart #{payload.multipart?} and signature multipart #{signature.multipart?}\"",
"return",
"end",
"## this probably will never happen",
"if",
"payload",
".",
"header",
".",
"content_type",
"&&",
"payload",
".",
"header",
".",
"content_type",
".",
"downcase",
"==",
"\"application/pgp-signature\"",
"warn_with_location",
"\"multipart/signed with payload content type #{payload.header.content_type}\"",
"return",
"end",
"if",
"signature",
".",
"header",
".",
"content_type",
"&&",
"signature",
".",
"header",
".",
"content_type",
".",
"downcase",
"!=",
"\"application/pgp-signature\"",
"## unknown signature type; just ignore.",
"#warn \"multipart/signed with signature content type #{signature.header.content_type}\"",
"return",
"end",
"[",
"CryptoManager",
".",
"verify",
"(",
"payload",
",",
"signature",
")",
",",
"message_to_chunks",
"(",
"payload",
")",
"]",
".",
"flatten",
".",
"compact",
"end"
] | here's where we handle decoding mime attachments. unfortunately
but unsurprisingly, the world of mime attachments is a bit of a
mess. as an empiricist, i'm basing the following behavior on
observed mail rather than on interpretations of rfcs, so probably
this will have to be tweaked.
the general behavior i want is: ignore content-disposition, at
least in so far as it suggests something being inline vs being an
attachment. (because really, that should be the recipient's
decision to make.) if a mime part is text/plain, OR if the user
decoding hook converts it, then decode it and display it
inline. for these decoded attachments, if it has associated
filename, then make it collapsable and individually saveable;
otherwise, treat it as regular body text.
everything else is just an attachment and is not displayed
inline.
so, in contrast to mutt, the user is not exposed to the workings
of the gruesome slaughterhouse and sausage factory that is a
mime-encoded message, but need only see the delicious end
product. | [
"here",
"s",
"where",
"we",
"handle",
"decoding",
"mime",
"attachments",
".",
"unfortunately",
"but",
"unsurprisingly",
"the",
"world",
"of",
"mime",
"attachments",
"is",
"a",
"bit",
"of",
"a",
"mess",
".",
"as",
"an",
"empiricist",
"i",
"m",
"basing",
"the",
"following",
"behavior",
"on",
"observed",
"mail",
"rather",
"than",
"on",
"interpretations",
"of",
"rfcs",
"so",
"probably",
"this",
"will",
"have",
"to",
"be",
"tweaked",
"."
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/message.rb#L405-L430 | train |
sup-heliotrope/sup | lib/sup/label.rb | Redwood.LabelManager.string_for | def string_for l
if RESERVED_LABELS.include? l
l.to_s.capitalize
else
l.to_s
end
end | ruby | def string_for l
if RESERVED_LABELS.include? l
l.to_s.capitalize
else
l.to_s
end
end | [
"def",
"string_for",
"l",
"if",
"RESERVED_LABELS",
".",
"include?",
"l",
"l",
".",
"to_s",
".",
"capitalize",
"else",
"l",
".",
"to_s",
"end",
"end"
] | reverse the label->string mapping, for convenience! | [
"reverse",
"the",
"label",
"-",
">",
"string",
"mapping",
"for",
"convenience!"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/label.rb#L47-L53 | train |
sup-heliotrope/sup | lib/sup/modes/scroll_mode.rb | Redwood.ScrollMode.search_goto_pos | def search_goto_pos line, leftcol, rightcol
search_goto_line line
if rightcol > self.rightcol # if it's occluded...
jump_to_col [rightcol - buffer.content_width + 1, 0].max # move right
end
end | ruby | def search_goto_pos line, leftcol, rightcol
search_goto_line line
if rightcol > self.rightcol # if it's occluded...
jump_to_col [rightcol - buffer.content_width + 1, 0].max # move right
end
end | [
"def",
"search_goto_pos",
"line",
",",
"leftcol",
",",
"rightcol",
"search_goto_line",
"line",
"if",
"rightcol",
">",
"self",
".",
"rightcol",
"# if it's occluded...",
"jump_to_col",
"[",
"rightcol",
"-",
"buffer",
".",
"content_width",
"+",
"1",
",",
"0",
"]",
".",
"max",
"# move right",
"end",
"end"
] | subclasses can override these three! | [
"subclasses",
"can",
"override",
"these",
"three!"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/modes/scroll_mode.rb#L89-L95 | train |
sup-heliotrope/sup | lib/sup/modes/scroll_mode.rb | Redwood.ScrollMode.jump_to_line | def jump_to_line l
l = l.clamp 0, lines - 1
return if @topline == l
@topline = l
@botline = [l + buffer.content_height, lines].min
buffer.mark_dirty
end | ruby | def jump_to_line l
l = l.clamp 0, lines - 1
return if @topline == l
@topline = l
@botline = [l + buffer.content_height, lines].min
buffer.mark_dirty
end | [
"def",
"jump_to_line",
"l",
"l",
"=",
"l",
".",
"clamp",
"0",
",",
"lines",
"-",
"1",
"return",
"if",
"@topline",
"==",
"l",
"@topline",
"=",
"l",
"@botline",
"=",
"[",
"l",
"+",
"buffer",
".",
"content_height",
",",
"lines",
"]",
".",
"min",
"buffer",
".",
"mark_dirty",
"end"
] | set top line to l | [
"set",
"top",
"line",
"to",
"l"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/modes/scroll_mode.rb#L123-L129 | train |
sup-heliotrope/sup | lib/sup/modes/line_cursor_mode.rb | Redwood.LineCursorMode.page_down | def page_down
## if we're on the last page, and it's not a full page, just move
## the cursor down to the bottom and assume we can't load anything
## else via the callbacks.
if topline > lines - buffer.content_height
set_cursor_pos(lines - 1)
## if we're on the last page, and it's a full page, try and load
## more lines via the callbacks and then shift the page down
elsif topline == lines - buffer.content_height
call_load_more_callbacks buffer.content_height
super
## otherwise, just move down
else
relpos = @curpos - topline
super
set_cursor_pos [topline + relpos, lines - 1].min
end
end | ruby | def page_down
## if we're on the last page, and it's not a full page, just move
## the cursor down to the bottom and assume we can't load anything
## else via the callbacks.
if topline > lines - buffer.content_height
set_cursor_pos(lines - 1)
## if we're on the last page, and it's a full page, try and load
## more lines via the callbacks and then shift the page down
elsif topline == lines - buffer.content_height
call_load_more_callbacks buffer.content_height
super
## otherwise, just move down
else
relpos = @curpos - topline
super
set_cursor_pos [topline + relpos, lines - 1].min
end
end | [
"def",
"page_down",
"## if we're on the last page, and it's not a full page, just move",
"## the cursor down to the bottom and assume we can't load anything",
"## else via the callbacks.",
"if",
"topline",
">",
"lines",
"-",
"buffer",
".",
"content_height",
"set_cursor_pos",
"(",
"lines",
"-",
"1",
")",
"## if we're on the last page, and it's a full page, try and load",
"## more lines via the callbacks and then shift the page down",
"elsif",
"topline",
"==",
"lines",
"-",
"buffer",
".",
"content_height",
"call_load_more_callbacks",
"buffer",
".",
"content_height",
"super",
"## otherwise, just move down",
"else",
"relpos",
"=",
"@curpos",
"-",
"topline",
"super",
"set_cursor_pos",
"[",
"topline",
"+",
"relpos",
",",
"lines",
"-",
"1",
"]",
".",
"min",
"end",
"end"
] | more complicated than one might think. three behaviors. | [
"more",
"complicated",
"than",
"one",
"might",
"think",
".",
"three",
"behaviors",
"."
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/modes/line_cursor_mode.rb#L161-L180 | train |
sup-heliotrope/sup | lib/sup/textfield.rb | Redwood.TextField.get_cursed_value | def get_cursed_value
return nil unless @field
x = Ncurses.curx
form_driver_key Ncurses::Form::REQ_VALIDATION
v = @field.field_buffer(0).gsub(/^\s+|\s+$/, "")
## cursor <= end of text
if x - @question.length - v.length <= 0
v
else # trailing spaces
v + (" " * (x - @question.length - v.length))
end
# ncurses returns a ASCII-8BIT (binary) string, which
# bytes presumably are of current charset encoding. we force_encoding
# so that the char representation / string is tagged will be the
# system locale and also hopefully the terminal/input encoding. an
# incorrectly configured terminal encoding (not matching the system
# encoding) will produce erronous results, but will also do that for
# a lot of other programs since it is impossible to detect which is
# which and what encoding the inputted byte chars are supposed to have.
v.force_encoding($encoding).fix_encoding!
end | ruby | def get_cursed_value
return nil unless @field
x = Ncurses.curx
form_driver_key Ncurses::Form::REQ_VALIDATION
v = @field.field_buffer(0).gsub(/^\s+|\s+$/, "")
## cursor <= end of text
if x - @question.length - v.length <= 0
v
else # trailing spaces
v + (" " * (x - @question.length - v.length))
end
# ncurses returns a ASCII-8BIT (binary) string, which
# bytes presumably are of current charset encoding. we force_encoding
# so that the char representation / string is tagged will be the
# system locale and also hopefully the terminal/input encoding. an
# incorrectly configured terminal encoding (not matching the system
# encoding) will produce erronous results, but will also do that for
# a lot of other programs since it is impossible to detect which is
# which and what encoding the inputted byte chars are supposed to have.
v.force_encoding($encoding).fix_encoding!
end | [
"def",
"get_cursed_value",
"return",
"nil",
"unless",
"@field",
"x",
"=",
"Ncurses",
".",
"curx",
"form_driver_key",
"Ncurses",
"::",
"Form",
"::",
"REQ_VALIDATION",
"v",
"=",
"@field",
".",
"field_buffer",
"(",
"0",
")",
".",
"gsub",
"(",
"/",
"\\s",
"\\s",
"/",
",",
"\"\"",
")",
"## cursor <= end of text",
"if",
"x",
"-",
"@question",
".",
"length",
"-",
"v",
".",
"length",
"<=",
"0",
"v",
"else",
"# trailing spaces",
"v",
"+",
"(",
"\" \"",
"*",
"(",
"x",
"-",
"@question",
".",
"length",
"-",
"v",
".",
"length",
")",
")",
"end",
"# ncurses returns a ASCII-8BIT (binary) string, which",
"# bytes presumably are of current charset encoding. we force_encoding",
"# so that the char representation / string is tagged will be the",
"# system locale and also hopefully the terminal/input encoding. an",
"# incorrectly configured terminal encoding (not matching the system",
"# encoding) will produce erronous results, but will also do that for",
"# a lot of other programs since it is impossible to detect which is",
"# which and what encoding the inputted byte chars are supposed to have.",
"v",
".",
"force_encoding",
"(",
"$encoding",
")",
".",
"fix_encoding!",
"end"
] | ncurses inanity wrapper
DO NOT READ THIS CODE. YOU WILL GO MAD. | [
"ncurses",
"inanity",
"wrapper"
] | 36f95462e3014c354c577d63a78ba030c4b84474 | https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/textfield.rb#L177-L200 | train |
websocket-rails/websocket-rails | lib/websocket_rails/base_controller.rb | WebsocketRails.BaseController.trigger_success | def trigger_success(data=nil)
event.success = true
event.data = data
event.trigger
end | ruby | def trigger_success(data=nil)
event.success = true
event.data = data
event.trigger
end | [
"def",
"trigger_success",
"(",
"data",
"=",
"nil",
")",
"event",
".",
"success",
"=",
"true",
"event",
".",
"data",
"=",
"data",
"event",
".",
"trigger",
"end"
] | Trigger the success callback function attached to the client event that triggered
this action. The object passed to this method will be passed as an argument to
the callback function on the client. | [
"Trigger",
"the",
"success",
"callback",
"function",
"attached",
"to",
"the",
"client",
"event",
"that",
"triggered",
"this",
"action",
".",
"The",
"object",
"passed",
"to",
"this",
"method",
"will",
"be",
"passed",
"as",
"an",
"argument",
"to",
"the",
"callback",
"function",
"on",
"the",
"client",
"."
] | 0ee9e97b19e1f8250c18ded08c71647a51669122 | https://github.com/websocket-rails/websocket-rails/blob/0ee9e97b19e1f8250c18ded08c71647a51669122/lib/websocket_rails/base_controller.rb#L100-L104 | train |
websocket-rails/websocket-rails | lib/websocket_rails/base_controller.rb | WebsocketRails.BaseController.trigger_failure | def trigger_failure(data=nil)
event.success = false
event.data = data
event.trigger
end | ruby | def trigger_failure(data=nil)
event.success = false
event.data = data
event.trigger
end | [
"def",
"trigger_failure",
"(",
"data",
"=",
"nil",
")",
"event",
".",
"success",
"=",
"false",
"event",
".",
"data",
"=",
"data",
"event",
".",
"trigger",
"end"
] | Trigger the failure callback function attached to the client event that triggered
this action. The object passed to this method will be passed as an argument to
the callback function on the client. | [
"Trigger",
"the",
"failure",
"callback",
"function",
"attached",
"to",
"the",
"client",
"event",
"that",
"triggered",
"this",
"action",
".",
"The",
"object",
"passed",
"to",
"this",
"method",
"will",
"be",
"passed",
"as",
"an",
"argument",
"to",
"the",
"callback",
"function",
"on",
"the",
"client",
"."
] | 0ee9e97b19e1f8250c18ded08c71647a51669122 | https://github.com/websocket-rails/websocket-rails/blob/0ee9e97b19e1f8250c18ded08c71647a51669122/lib/websocket_rails/base_controller.rb#L109-L113 | train |
websocket-rails/websocket-rails | lib/websocket_rails/base_controller.rb | WebsocketRails.BaseController.send_message | def send_message(event_name, message, options={})
options.merge! :connection => connection, :data => message
event = Event.new( event_name, options )
@_dispatcher.send_message event if @_dispatcher.respond_to?(:send_message)
end | ruby | def send_message(event_name, message, options={})
options.merge! :connection => connection, :data => message
event = Event.new( event_name, options )
@_dispatcher.send_message event if @_dispatcher.respond_to?(:send_message)
end | [
"def",
"send_message",
"(",
"event_name",
",",
"message",
",",
"options",
"=",
"{",
"}",
")",
"options",
".",
"merge!",
":connection",
"=>",
"connection",
",",
":data",
"=>",
"message",
"event",
"=",
"Event",
".",
"new",
"(",
"event_name",
",",
"options",
")",
"@_dispatcher",
".",
"send_message",
"event",
"if",
"@_dispatcher",
".",
"respond_to?",
"(",
":send_message",
")",
"end"
] | Sends a message to the client that initiated the current event being executed. Messages
are serialized as JSON into a two element Array where the first element is the event
and the second element is the message that was passed, typically a Hash.
To send an event under a namespace, add the `:namespace => :target_namespace` option.
send_message :new_message, message_hash, :namespace => :product
Nested namespaces can be passed as an array like the following:
send_message :new, message_hash, :namespace => [:products,:glasses]
See the {EventMap} documentation for more on mapping namespaced actions. | [
"Sends",
"a",
"message",
"to",
"the",
"client",
"that",
"initiated",
"the",
"current",
"event",
"being",
"executed",
".",
"Messages",
"are",
"serialized",
"as",
"JSON",
"into",
"a",
"two",
"element",
"Array",
"where",
"the",
"first",
"element",
"is",
"the",
"event",
"and",
"the",
"second",
"element",
"is",
"the",
"message",
"that",
"was",
"passed",
"typically",
"a",
"Hash",
"."
] | 0ee9e97b19e1f8250c18ded08c71647a51669122 | https://github.com/websocket-rails/websocket-rails/blob/0ee9e97b19e1f8250c18ded08c71647a51669122/lib/websocket_rails/base_controller.rb#L142-L146 | train |
websocket-rails/websocket-rails | lib/websocket_rails/controller_factory.rb | WebsocketRails.ControllerFactory.reload! | def reload!(controller)
return controller unless defined?(Rails) and !Rails.configuration.cache_classes
# we don't reload our own controller as we assume it provide as 'library'
unless controller.name == "WebsocketRails::InternalController"
class_name = controller.name
filename = class_name.underscore
load "#{filename}.rb"
return class_name.constantize
end
return controller
end | ruby | def reload!(controller)
return controller unless defined?(Rails) and !Rails.configuration.cache_classes
# we don't reload our own controller as we assume it provide as 'library'
unless controller.name == "WebsocketRails::InternalController"
class_name = controller.name
filename = class_name.underscore
load "#{filename}.rb"
return class_name.constantize
end
return controller
end | [
"def",
"reload!",
"(",
"controller",
")",
"return",
"controller",
"unless",
"defined?",
"(",
"Rails",
")",
"and",
"!",
"Rails",
".",
"configuration",
".",
"cache_classes",
"# we don't reload our own controller as we assume it provide as 'library'",
"unless",
"controller",
".",
"name",
"==",
"\"WebsocketRails::InternalController\"",
"class_name",
"=",
"controller",
".",
"name",
"filename",
"=",
"class_name",
".",
"underscore",
"load",
"\"#{filename}.rb\"",
"return",
"class_name",
".",
"constantize",
"end",
"return",
"controller",
"end"
] | Reloads the controller class to pick up code changes
while in the development environment. | [
"Reloads",
"the",
"controller",
"class",
"to",
"pick",
"up",
"code",
"changes",
"while",
"in",
"the",
"development",
"environment",
"."
] | 0ee9e97b19e1f8250c18ded08c71647a51669122 | https://github.com/websocket-rails/websocket-rails/blob/0ee9e97b19e1f8250c18ded08c71647a51669122/lib/websocket_rails/controller_factory.rb#L66-L77 | train |
websocket-rails/websocket-rails | lib/websocket_rails/connection_manager.rb | WebsocketRails.ConnectionManager.call | def call(env)
request = ActionDispatch::Request.new(env)
if request.post?
response = parse_incoming_event(request.params)
else
response = open_connection(request)
end
response
rescue InvalidConnectionError
BadRequestResponse
end | ruby | def call(env)
request = ActionDispatch::Request.new(env)
if request.post?
response = parse_incoming_event(request.params)
else
response = open_connection(request)
end
response
rescue InvalidConnectionError
BadRequestResponse
end | [
"def",
"call",
"(",
"env",
")",
"request",
"=",
"ActionDispatch",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"if",
"request",
".",
"post?",
"response",
"=",
"parse_incoming_event",
"(",
"request",
".",
"params",
")",
"else",
"response",
"=",
"open_connection",
"(",
"request",
")",
"end",
"response",
"rescue",
"InvalidConnectionError",
"BadRequestResponse",
"end"
] | Primary entry point for the Rack application | [
"Primary",
"entry",
"point",
"for",
"the",
"Rack",
"application"
] | 0ee9e97b19e1f8250c18ded08c71647a51669122 | https://github.com/websocket-rails/websocket-rails/blob/0ee9e97b19e1f8250c18ded08c71647a51669122/lib/websocket_rails/connection_manager.rb#L49-L61 | train |
AlchemyCMS/alchemy_cms | app/controllers/concerns/alchemy/legacy_page_redirects.rb | Alchemy.LegacyPageRedirects.legacy_page_redirect_url | def legacy_page_redirect_url
page = last_legacy_url.page
return unless page
alchemy.show_page_path(
locale: prefix_locale? ? page.language_code : nil,
urlname: page.urlname
)
end | ruby | def legacy_page_redirect_url
page = last_legacy_url.page
return unless page
alchemy.show_page_path(
locale: prefix_locale? ? page.language_code : nil,
urlname: page.urlname
)
end | [
"def",
"legacy_page_redirect_url",
"page",
"=",
"last_legacy_url",
".",
"page",
"return",
"unless",
"page",
"alchemy",
".",
"show_page_path",
"(",
"locale",
":",
"prefix_locale?",
"?",
"page",
".",
"language_code",
":",
"nil",
",",
"urlname",
":",
"page",
".",
"urlname",
")",
"end"
] | Use the bare minimum to redirect to legacy page
Don't use query string of legacy urlname.
This drops the given query string. | [
"Use",
"the",
"bare",
"minimum",
"to",
"redirect",
"to",
"legacy",
"page"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/concerns/alchemy/legacy_page_redirects.rb#L33-L41 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/element/element_contents.rb | Alchemy.Element::ElementContents.update_contents | def update_contents(contents_attributes)
return true if contents_attributes.nil?
contents.each do |content|
content_hash = contents_attributes[content.id.to_s] || next
content.update_essence(content_hash) || errors.add(:base, :essence_validation_failed)
end
errors.blank?
end | ruby | def update_contents(contents_attributes)
return true if contents_attributes.nil?
contents.each do |content|
content_hash = contents_attributes[content.id.to_s] || next
content.update_essence(content_hash) || errors.add(:base, :essence_validation_failed)
end
errors.blank?
end | [
"def",
"update_contents",
"(",
"contents_attributes",
")",
"return",
"true",
"if",
"contents_attributes",
".",
"nil?",
"contents",
".",
"each",
"do",
"|",
"content",
"|",
"content_hash",
"=",
"contents_attributes",
"[",
"content",
".",
"id",
".",
"to_s",
"]",
"||",
"next",
"content",
".",
"update_essence",
"(",
"content_hash",
")",
"||",
"errors",
".",
"add",
"(",
":base",
",",
":essence_validation_failed",
")",
"end",
"errors",
".",
"blank?",
"end"
] | Updates all related contents by calling +update_essence+ on each of them.
@param contents_attributes [Hash]
Hash of contents attributes.
The keys has to be the #id of the content to update.
The values a Hash of attribute names and values
@return [Boolean]
True if +errors+ are blank or +contents_attributes+ hash is nil
== Example
@element.update_contents(
"1" => {ingredient: "Title"},
"2" => {link: "https://google.com"}
) | [
"Updates",
"all",
"related",
"contents",
"by",
"calling",
"+",
"update_essence",
"+",
"on",
"each",
"of",
"them",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/element/element_contents.rb#L46-L53 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/element/element_contents.rb | Alchemy.Element::ElementContents.copy_contents_to | def copy_contents_to(element)
contents.map do |content|
Content.copy(content, element_id: element.id)
end
end | ruby | def copy_contents_to(element)
contents.map do |content|
Content.copy(content, element_id: element.id)
end
end | [
"def",
"copy_contents_to",
"(",
"element",
")",
"contents",
".",
"map",
"do",
"|",
"content",
"|",
"Content",
".",
"copy",
"(",
"content",
",",
"element_id",
":",
"element",
".",
"id",
")",
"end",
"end"
] | Copy current content's contents to given target element | [
"Copy",
"current",
"content",
"s",
"contents",
"to",
"given",
"target",
"element"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/element/element_contents.rb#L56-L60 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/element/element_contents.rb | Alchemy.Element::ElementContents.content_definition_for | def content_definition_for(content_name)
if content_definitions.blank?
log_warning "Element #{name} is missing the content definition for #{content_name}"
nil
else
content_definitions.detect { |d| d['name'] == content_name }
end
end | ruby | def content_definition_for(content_name)
if content_definitions.blank?
log_warning "Element #{name} is missing the content definition for #{content_name}"
nil
else
content_definitions.detect { |d| d['name'] == content_name }
end
end | [
"def",
"content_definition_for",
"(",
"content_name",
")",
"if",
"content_definitions",
".",
"blank?",
"log_warning",
"\"Element #{name} is missing the content definition for #{content_name}\"",
"nil",
"else",
"content_definitions",
".",
"detect",
"{",
"|",
"d",
"|",
"d",
"[",
"'name'",
"]",
"==",
"content_name",
"}",
"end",
"end"
] | Returns the definition for given content_name | [
"Returns",
"the",
"definition",
"for",
"given",
"content_name"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/element/element_contents.rb#L97-L104 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/element/element_contents.rb | Alchemy.Element::ElementContents.richtext_contents_ids | def richtext_contents_ids
# This is not very efficient SQL wise I know, but we need to iterate
# recursivly through all descendent elements and I don't know how to do this
# in pure SQL. Anyone with a better idea is welcome to submit a patch.
ids = contents.select(&:has_tinymce?).collect(&:id)
expanded_nested_elements = nested_elements.expanded
if expanded_nested_elements.present?
ids += expanded_nested_elements.collect(&:richtext_contents_ids)
end
ids.flatten
end | ruby | def richtext_contents_ids
# This is not very efficient SQL wise I know, but we need to iterate
# recursivly through all descendent elements and I don't know how to do this
# in pure SQL. Anyone with a better idea is welcome to submit a patch.
ids = contents.select(&:has_tinymce?).collect(&:id)
expanded_nested_elements = nested_elements.expanded
if expanded_nested_elements.present?
ids += expanded_nested_elements.collect(&:richtext_contents_ids)
end
ids.flatten
end | [
"def",
"richtext_contents_ids",
"# This is not very efficient SQL wise I know, but we need to iterate",
"# recursivly through all descendent elements and I don't know how to do this",
"# in pure SQL. Anyone with a better idea is welcome to submit a patch.",
"ids",
"=",
"contents",
".",
"select",
"(",
":has_tinymce?",
")",
".",
"collect",
"(",
":id",
")",
"expanded_nested_elements",
"=",
"nested_elements",
".",
"expanded",
"if",
"expanded_nested_elements",
".",
"present?",
"ids",
"+=",
"expanded_nested_elements",
".",
"collect",
"(",
":richtext_contents_ids",
")",
"end",
"ids",
".",
"flatten",
"end"
] | Returns an array of all EssenceRichtext contents ids from elements
This is used to re-initialize the TinyMCE editor in the element editor. | [
"Returns",
"an",
"array",
"of",
"all",
"EssenceRichtext",
"contents",
"ids",
"from",
"elements"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/element/element_contents.rb#L110-L120 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/element/element_contents.rb | Alchemy.Element::ElementContents.create_contents | def create_contents
definition.fetch('contents', []).each do |attributes|
Content.create(attributes.merge(element: self))
end
end | ruby | def create_contents
definition.fetch('contents', []).each do |attributes|
Content.create(attributes.merge(element: self))
end
end | [
"def",
"create_contents",
"definition",
".",
"fetch",
"(",
"'contents'",
",",
"[",
"]",
")",
".",
"each",
"do",
"|",
"attributes",
"|",
"Content",
".",
"create",
"(",
"attributes",
".",
"merge",
"(",
"element",
":",
"self",
")",
")",
"end",
"end"
] | creates the contents for this element as described in the elements.yml | [
"creates",
"the",
"contents",
"for",
"this",
"element",
"as",
"described",
"in",
"the",
"elements",
".",
"yml"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/element/element_contents.rb#L141-L145 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/page/page_elements.rb | Alchemy.Page::PageElements.available_element_definitions | def available_element_definitions(only_element_named = nil)
@_element_definitions ||= if only_element_named
definition = Element.definition_by_name(only_element_named)
element_definitions_by_name(definition['nestable_elements'])
else
element_definitions
end
return [] if @_element_definitions.blank?
@_existing_element_names = elements_including_fixed.pluck(:name)
delete_unique_element_definitions!
delete_outnumbered_element_definitions!
@_element_definitions
end | ruby | def available_element_definitions(only_element_named = nil)
@_element_definitions ||= if only_element_named
definition = Element.definition_by_name(only_element_named)
element_definitions_by_name(definition['nestable_elements'])
else
element_definitions
end
return [] if @_element_definitions.blank?
@_existing_element_names = elements_including_fixed.pluck(:name)
delete_unique_element_definitions!
delete_outnumbered_element_definitions!
@_element_definitions
end | [
"def",
"available_element_definitions",
"(",
"only_element_named",
"=",
"nil",
")",
"@_element_definitions",
"||=",
"if",
"only_element_named",
"definition",
"=",
"Element",
".",
"definition_by_name",
"(",
"only_element_named",
")",
"element_definitions_by_name",
"(",
"definition",
"[",
"'nestable_elements'",
"]",
")",
"else",
"element_definitions",
"end",
"return",
"[",
"]",
"if",
"@_element_definitions",
".",
"blank?",
"@_existing_element_names",
"=",
"elements_including_fixed",
".",
"pluck",
"(",
":name",
")",
"delete_unique_element_definitions!",
"delete_outnumbered_element_definitions!",
"@_element_definitions",
"end"
] | All available element definitions that can actually be placed on current page.
It extracts all definitions that are unique or limited and already on page.
== Example of unique element:
- name: headline
unique: true
contents:
- name: headline
type: EssenceText
== Example of limited element:
- name: article
amount: 2
contents:
- name: text
type: EssenceRichtext | [
"All",
"available",
"element",
"definitions",
"that",
"can",
"actually",
"be",
"placed",
"on",
"current",
"page",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/page/page_elements.rb#L84-L99 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/page/page_elements.rb | Alchemy.Page::PageElements.available_elements_within_current_scope | def available_elements_within_current_scope(parent)
@_available_elements = if parent
parents_unique_nested_elements = parent.nested_elements.where(unique: true).pluck(:name)
available_element_definitions(parent.name).reject do |e|
parents_unique_nested_elements.include? e['name']
end
else
available_element_definitions
end
end | ruby | def available_elements_within_current_scope(parent)
@_available_elements = if parent
parents_unique_nested_elements = parent.nested_elements.where(unique: true).pluck(:name)
available_element_definitions(parent.name).reject do |e|
parents_unique_nested_elements.include? e['name']
end
else
available_element_definitions
end
end | [
"def",
"available_elements_within_current_scope",
"(",
"parent",
")",
"@_available_elements",
"=",
"if",
"parent",
"parents_unique_nested_elements",
"=",
"parent",
".",
"nested_elements",
".",
"where",
"(",
"unique",
":",
"true",
")",
".",
"pluck",
"(",
":name",
")",
"available_element_definitions",
"(",
"parent",
".",
"name",
")",
".",
"reject",
"do",
"|",
"e",
"|",
"parents_unique_nested_elements",
".",
"include?",
"e",
"[",
"'name'",
"]",
"end",
"else",
"available_element_definitions",
"end",
"end"
] | Available element definitions excluding nested unique elements. | [
"Available",
"element",
"definitions",
"excluding",
"nested",
"unique",
"elements",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/page/page_elements.rb#L109-L118 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/page/page_elements.rb | Alchemy.Page::PageElements.descendent_element_definitions | def descendent_element_definitions
definitions = element_definitions_by_name(element_definition_names)
definitions.select { |d| d.key?('nestable_elements') }.each do |d|
definitions += element_definitions_by_name(d['nestable_elements'])
end
definitions.uniq { |d| d['name'] }
end | ruby | def descendent_element_definitions
definitions = element_definitions_by_name(element_definition_names)
definitions.select { |d| d.key?('nestable_elements') }.each do |d|
definitions += element_definitions_by_name(d['nestable_elements'])
end
definitions.uniq { |d| d['name'] }
end | [
"def",
"descendent_element_definitions",
"definitions",
"=",
"element_definitions_by_name",
"(",
"element_definition_names",
")",
"definitions",
".",
"select",
"{",
"|",
"d",
"|",
"d",
".",
"key?",
"(",
"'nestable_elements'",
")",
"}",
".",
"each",
"do",
"|",
"d",
"|",
"definitions",
"+=",
"element_definitions_by_name",
"(",
"d",
"[",
"'nestable_elements'",
"]",
")",
"end",
"definitions",
".",
"uniq",
"{",
"|",
"d",
"|",
"d",
"[",
"'name'",
"]",
"}",
"end"
] | All element definitions defined for page's page layout including nestable element definitions | [
"All",
"element",
"definitions",
"defined",
"for",
"page",
"s",
"page",
"layout",
"including",
"nestable",
"element",
"definitions"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/page/page_elements.rb#L131-L137 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/page/page_elements.rb | Alchemy.Page::PageElements.generate_elements | def generate_elements
elements_already_on_page = elements_including_fixed.pluck(:name)
definition.fetch('autogenerate', []).each do |element_name|
next if elements_already_on_page.include?(element_name)
Element.create(page: self, name: element_name)
end
end | ruby | def generate_elements
elements_already_on_page = elements_including_fixed.pluck(:name)
definition.fetch('autogenerate', []).each do |element_name|
next if elements_already_on_page.include?(element_name)
Element.create(page: self, name: element_name)
end
end | [
"def",
"generate_elements",
"elements_already_on_page",
"=",
"elements_including_fixed",
".",
"pluck",
"(",
":name",
")",
"definition",
".",
"fetch",
"(",
"'autogenerate'",
",",
"[",
"]",
")",
".",
"each",
"do",
"|",
"element_name",
"|",
"next",
"if",
"elements_already_on_page",
".",
"include?",
"(",
"element_name",
")",
"Element",
".",
"create",
"(",
"page",
":",
"self",
",",
"name",
":",
"element_name",
")",
"end",
"end"
] | Looks in the page_layout descripion, if there are elements to autogenerate.
And if so, it generates them. | [
"Looks",
"in",
"the",
"page_layout",
"descripion",
"if",
"there",
"are",
"elements",
"to",
"autogenerate",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/page/page_elements.rb#L198-L204 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/page/page_elements.rb | Alchemy.Page::PageElements.delete_outnumbered_element_definitions! | def delete_outnumbered_element_definitions!
@_element_definitions.delete_if do |element|
outnumbered = @_existing_element_names.select { |name| name == element['name'] }
element['amount'] && outnumbered.count >= element['amount'].to_i
end
end | ruby | def delete_outnumbered_element_definitions!
@_element_definitions.delete_if do |element|
outnumbered = @_existing_element_names.select { |name| name == element['name'] }
element['amount'] && outnumbered.count >= element['amount'].to_i
end
end | [
"def",
"delete_outnumbered_element_definitions!",
"@_element_definitions",
".",
"delete_if",
"do",
"|",
"element",
"|",
"outnumbered",
"=",
"@_existing_element_names",
".",
"select",
"{",
"|",
"name",
"|",
"name",
"==",
"element",
"[",
"'name'",
"]",
"}",
"element",
"[",
"'amount'",
"]",
"&&",
"outnumbered",
".",
"count",
">=",
"element",
"[",
"'amount'",
"]",
".",
"to_i",
"end",
"end"
] | Deletes limited and outnumbered definitions from @_element_definitions. | [
"Deletes",
"limited",
"and",
"outnumbered",
"definitions",
"from"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/page/page_elements.rb#L233-L238 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/on_page_layout.rb | Alchemy.OnPageLayout.on_page_layout | def on_page_layout(page_layouts, callback = nil, &block)
callback = block || callback
[page_layouts].flatten.each do |page_layout|
if callback
OnPageLayout.register_callback(page_layout, callback)
else
raise ArgumentError,
"You need to either pass a block or method name as a callback for `on_page_layout`"
end
end
end | ruby | def on_page_layout(page_layouts, callback = nil, &block)
callback = block || callback
[page_layouts].flatten.each do |page_layout|
if callback
OnPageLayout.register_callback(page_layout, callback)
else
raise ArgumentError,
"You need to either pass a block or method name as a callback for `on_page_layout`"
end
end
end | [
"def",
"on_page_layout",
"(",
"page_layouts",
",",
"callback",
"=",
"nil",
",",
"&",
"block",
")",
"callback",
"=",
"block",
"||",
"callback",
"[",
"page_layouts",
"]",
".",
"flatten",
".",
"each",
"do",
"|",
"page_layout",
"|",
"if",
"callback",
"OnPageLayout",
".",
"register_callback",
"(",
"page_layout",
",",
"callback",
")",
"else",
"raise",
"ArgumentError",
",",
"\"You need to either pass a block or method name as a callback for `on_page_layout`\"",
"end",
"end",
"end"
] | Define a page layout callback
Pass a block or method name in which you have the +@page+ object available and can do
everything as if you were in a normal controller action.
Pass a +Alchemy::PageLayout+ name, an array of names, or +:all+ to
evaluate the callback on either some specific or all the pages. | [
"Define",
"a",
"page",
"layout",
"callback"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/on_page_layout.rb#L62-L72 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/content.rb | Alchemy.Content.serialize | def serialize
{
name: name,
value: serialized_ingredient,
link: essence.try(:link)
}.delete_if { |_k, v| v.blank? }
end | ruby | def serialize
{
name: name,
value: serialized_ingredient,
link: essence.try(:link)
}.delete_if { |_k, v| v.blank? }
end | [
"def",
"serialize",
"{",
"name",
":",
"name",
",",
"value",
":",
"serialized_ingredient",
",",
"link",
":",
"essence",
".",
"try",
"(",
":link",
")",
"}",
".",
"delete_if",
"{",
"|",
"_k",
",",
"v",
"|",
"v",
".",
"blank?",
"}",
"end"
] | Serialized object representation for json api | [
"Serialized",
"object",
"representation",
"for",
"json",
"api"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/content.rb#L134-L140 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/content.rb | Alchemy.Content.update_essence | def update_essence(params = {})
raise EssenceMissingError if essence.nil?
if essence.update(params)
return true
else
errors.add(:essence, :validation_failed)
return false
end
end | ruby | def update_essence(params = {})
raise EssenceMissingError if essence.nil?
if essence.update(params)
return true
else
errors.add(:essence, :validation_failed)
return false
end
end | [
"def",
"update_essence",
"(",
"params",
"=",
"{",
"}",
")",
"raise",
"EssenceMissingError",
"if",
"essence",
".",
"nil?",
"if",
"essence",
".",
"update",
"(",
"params",
")",
"return",
"true",
"else",
"errors",
".",
"add",
"(",
":essence",
",",
":validation_failed",
")",
"return",
"false",
"end",
"end"
] | Updates the essence.
Called from +Alchemy::Element#update_contents+
Adds errors to self.base if essence validation fails. | [
"Updates",
"the",
"essence",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/content.rb#L163-L171 | train |
AlchemyCMS/alchemy_cms | app/helpers/alchemy/elements_block_helper.rb | Alchemy.ElementsBlockHelper.element_view_for | def element_view_for(element, options = {})
options = {
tag: :div,
id: element_dom_id(element),
class: element.name,
tags_formatter: ->(tags) { tags.join(" ") }
}.merge(options)
# capture inner template block
output = capture do
yield ElementViewHelper.new(self, element: element) if block_given?
end
# wrap output in a useful DOM element
if tag = options.delete(:tag)
# add preview attributes
options.merge!(element_preview_code_attributes(element))
# add tags
if tags_formatter = options.delete(:tags_formatter)
options.merge!(element_tags_attributes(element, formatter: tags_formatter))
end
output = content_tag(tag, output, options)
end
# that's it!
output
end | ruby | def element_view_for(element, options = {})
options = {
tag: :div,
id: element_dom_id(element),
class: element.name,
tags_formatter: ->(tags) { tags.join(" ") }
}.merge(options)
# capture inner template block
output = capture do
yield ElementViewHelper.new(self, element: element) if block_given?
end
# wrap output in a useful DOM element
if tag = options.delete(:tag)
# add preview attributes
options.merge!(element_preview_code_attributes(element))
# add tags
if tags_formatter = options.delete(:tags_formatter)
options.merge!(element_tags_attributes(element, formatter: tags_formatter))
end
output = content_tag(tag, output, options)
end
# that's it!
output
end | [
"def",
"element_view_for",
"(",
"element",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"tag",
":",
":div",
",",
"id",
":",
"element_dom_id",
"(",
"element",
")",
",",
"class",
":",
"element",
".",
"name",
",",
"tags_formatter",
":",
"->",
"(",
"tags",
")",
"{",
"tags",
".",
"join",
"(",
"\" \"",
")",
"}",
"}",
".",
"merge",
"(",
"options",
")",
"# capture inner template block",
"output",
"=",
"capture",
"do",
"yield",
"ElementViewHelper",
".",
"new",
"(",
"self",
",",
"element",
":",
"element",
")",
"if",
"block_given?",
"end",
"# wrap output in a useful DOM element",
"if",
"tag",
"=",
"options",
".",
"delete",
"(",
":tag",
")",
"# add preview attributes",
"options",
".",
"merge!",
"(",
"element_preview_code_attributes",
"(",
"element",
")",
")",
"# add tags",
"if",
"tags_formatter",
"=",
"options",
".",
"delete",
"(",
":tags_formatter",
")",
"options",
".",
"merge!",
"(",
"element_tags_attributes",
"(",
"element",
",",
"formatter",
":",
"tags_formatter",
")",
")",
"end",
"output",
"=",
"content_tag",
"(",
"tag",
",",
"output",
",",
"options",
")",
"end",
"# that's it!",
"output",
"end"
] | Block-level helper for element views. Constructs a DOM element wrapping
your content element and provides a block helper object you can use for
concise access to Alchemy's various helpers.
=== Example:
<%= element_view_for(element) do |el| %>
<%= el.render :title %>
<%= el.render :body %>
<%= link_to "Go!", el.ingredient(:target_url) %>
<% end %>
You can override the tag, ID and class used for the generated DOM
element:
<%= element_view_for(element, tag: 'span', id: 'my_id', class: 'thing') do |el| %>
<%- ... %>
<% end %>
If you don't want your view to be wrapped into an extra element, simply set
`tag` to `false`:
<%= element_view_for(element, tag: false) do |el| %>
<%- ... %>
<% end %>
@param [Alchemy::Element] element
The element to display.
@param [Hash] options
Additional options.
@option options :tag (:div)
The HTML tag to be used for the wrapping element.
@option options :id (the element's dom_id)
The wrapper tag's DOM ID.
@option options :class (the element's essence name)
The wrapper tag's DOM class.
@option options :tags_formatter
A lambda used for formatting the element's tags (see Alchemy::ElementsHelper::element_tags_attributes). Set to +false+ to not include tags in the wrapper element. | [
"Block",
"-",
"level",
"helper",
"for",
"element",
"views",
".",
"Constructs",
"a",
"DOM",
"element",
"wrapping",
"your",
"content",
"element",
"and",
"provides",
"a",
"block",
"helper",
"object",
"you",
"can",
"use",
"for",
"concise",
"access",
"to",
"Alchemy",
"s",
"various",
"helpers",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/elements_block_helper.rb#L106-L134 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/picture/url.rb | Alchemy.Picture::Url.url | def url(options = {})
image = image_file
raise MissingImageFileError, "Missing image file for #{inspect}" if image.nil?
image = processed_image(image, options)
image = encoded_image(image, options)
image.url(options.except(*TRANSFORMATION_OPTIONS).merge(name: name))
rescue MissingImageFileError, WrongImageFormatError => e
log_warning e.message
nil
end | ruby | def url(options = {})
image = image_file
raise MissingImageFileError, "Missing image file for #{inspect}" if image.nil?
image = processed_image(image, options)
image = encoded_image(image, options)
image.url(options.except(*TRANSFORMATION_OPTIONS).merge(name: name))
rescue MissingImageFileError, WrongImageFormatError => e
log_warning e.message
nil
end | [
"def",
"url",
"(",
"options",
"=",
"{",
"}",
")",
"image",
"=",
"image_file",
"raise",
"MissingImageFileError",
",",
"\"Missing image file for #{inspect}\"",
"if",
"image",
".",
"nil?",
"image",
"=",
"processed_image",
"(",
"image",
",",
"options",
")",
"image",
"=",
"encoded_image",
"(",
"image",
",",
"options",
")",
"image",
".",
"url",
"(",
"options",
".",
"except",
"(",
"TRANSFORMATION_OPTIONS",
")",
".",
"merge",
"(",
"name",
":",
"name",
")",
")",
"rescue",
"MissingImageFileError",
",",
"WrongImageFormatError",
"=>",
"e",
"log_warning",
"e",
".",
"message",
"nil",
"end"
] | Returns a path to picture for use inside a image_tag helper.
Any additional options are passed to the url_helper, so you can add arguments to your url.
Example:
<%= image_tag picture.url(size: '320x200', format: 'png') %> | [
"Returns",
"a",
"path",
"to",
"picture",
"for",
"use",
"inside",
"a",
"image_tag",
"helper",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/picture/url.rb#L26-L38 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/picture/url.rb | Alchemy.Picture::Url.processed_image | def processed_image(image, options = {})
size = options[:size]
upsample = !!options[:upsample]
return image unless size.present? && has_convertible_format?
if options[:crop]
crop(size, options[:crop_from], options[:crop_size], upsample)
else
resize(size, upsample)
end
end | ruby | def processed_image(image, options = {})
size = options[:size]
upsample = !!options[:upsample]
return image unless size.present? && has_convertible_format?
if options[:crop]
crop(size, options[:crop_from], options[:crop_size], upsample)
else
resize(size, upsample)
end
end | [
"def",
"processed_image",
"(",
"image",
",",
"options",
"=",
"{",
"}",
")",
"size",
"=",
"options",
"[",
":size",
"]",
"upsample",
"=",
"!",
"!",
"options",
"[",
":upsample",
"]",
"return",
"image",
"unless",
"size",
".",
"present?",
"&&",
"has_convertible_format?",
"if",
"options",
"[",
":crop",
"]",
"crop",
"(",
"size",
",",
"options",
"[",
":crop_from",
"]",
",",
"options",
"[",
":crop_size",
"]",
",",
"upsample",
")",
"else",
"resize",
"(",
"size",
",",
"upsample",
")",
"end",
"end"
] | Returns the processed image dependent of size and cropping parameters | [
"Returns",
"the",
"processed",
"image",
"dependent",
"of",
"size",
"and",
"cropping",
"parameters"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/picture/url.rb#L43-L54 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/picture/url.rb | Alchemy.Picture::Url.encoded_image | def encoded_image(image, options = {})
target_format = options[:format] || default_render_format
unless target_format.in?(Alchemy::Picture.allowed_filetypes)
raise WrongImageFormatError.new(self, target_format)
end
options = {
flatten: target_format != 'gif' && image_file_format == 'gif'
}.merge(options)
encoding_options = []
if target_format =~ /jpe?g/
quality = options[:quality] || Config.get(:output_image_jpg_quality)
encoding_options << "-quality #{quality}"
end
if options[:flatten]
encoding_options << '-flatten'
end
convertion_needed = target_format != image_file_format || encoding_options.present?
if has_convertible_format? && convertion_needed
image = image.encode(target_format, encoding_options.join(' '))
end
image
end | ruby | def encoded_image(image, options = {})
target_format = options[:format] || default_render_format
unless target_format.in?(Alchemy::Picture.allowed_filetypes)
raise WrongImageFormatError.new(self, target_format)
end
options = {
flatten: target_format != 'gif' && image_file_format == 'gif'
}.merge(options)
encoding_options = []
if target_format =~ /jpe?g/
quality = options[:quality] || Config.get(:output_image_jpg_quality)
encoding_options << "-quality #{quality}"
end
if options[:flatten]
encoding_options << '-flatten'
end
convertion_needed = target_format != image_file_format || encoding_options.present?
if has_convertible_format? && convertion_needed
image = image.encode(target_format, encoding_options.join(' '))
end
image
end | [
"def",
"encoded_image",
"(",
"image",
",",
"options",
"=",
"{",
"}",
")",
"target_format",
"=",
"options",
"[",
":format",
"]",
"||",
"default_render_format",
"unless",
"target_format",
".",
"in?",
"(",
"Alchemy",
"::",
"Picture",
".",
"allowed_filetypes",
")",
"raise",
"WrongImageFormatError",
".",
"new",
"(",
"self",
",",
"target_format",
")",
"end",
"options",
"=",
"{",
"flatten",
":",
"target_format",
"!=",
"'gif'",
"&&",
"image_file_format",
"==",
"'gif'",
"}",
".",
"merge",
"(",
"options",
")",
"encoding_options",
"=",
"[",
"]",
"if",
"target_format",
"=~",
"/",
"/",
"quality",
"=",
"options",
"[",
":quality",
"]",
"||",
"Config",
".",
"get",
"(",
":output_image_jpg_quality",
")",
"encoding_options",
"<<",
"\"-quality #{quality}\"",
"end",
"if",
"options",
"[",
":flatten",
"]",
"encoding_options",
"<<",
"'-flatten'",
"end",
"convertion_needed",
"=",
"target_format",
"!=",
"image_file_format",
"||",
"encoding_options",
".",
"present?",
"if",
"has_convertible_format?",
"&&",
"convertion_needed",
"image",
"=",
"image",
".",
"encode",
"(",
"target_format",
",",
"encoding_options",
".",
"join",
"(",
"' '",
")",
")",
"end",
"image",
"end"
] | Returns the encoded image
Flatten animated gifs, only if converting to a different format.
Can be overwritten via +options[:flatten]+. | [
"Returns",
"the",
"encoded",
"image"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/picture/url.rb#L61-L90 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/resources_helper.rb | Alchemy.ResourcesHelper.render_attribute | def render_attribute(resource, attribute, options = {})
attribute_value = resource.send(attribute[:name])
if attribute[:relation]
record = resource.send(attribute[:relation][:name])
value = record.present? ? record.send(attribute[:relation][:attr_method]) : Alchemy.t(:not_found)
elsif attribute_value && attribute[:type].to_s =~ /(date|time)/
localization_format = if attribute[:type] == :datetime
options[:datetime_format] || :'alchemy.default'
elsif attribute[:type] == :date
options[:date_format] || :'alchemy.default'
else
options[:time_format] || :'alchemy.time'
end
value = l(attribute_value, format: localization_format)
else
value = attribute_value
end
options.reverse_merge!(truncate: 50)
if options[:truncate]
value.to_s.truncate(options.fetch(:truncate, 50))
else
value
end
end | ruby | def render_attribute(resource, attribute, options = {})
attribute_value = resource.send(attribute[:name])
if attribute[:relation]
record = resource.send(attribute[:relation][:name])
value = record.present? ? record.send(attribute[:relation][:attr_method]) : Alchemy.t(:not_found)
elsif attribute_value && attribute[:type].to_s =~ /(date|time)/
localization_format = if attribute[:type] == :datetime
options[:datetime_format] || :'alchemy.default'
elsif attribute[:type] == :date
options[:date_format] || :'alchemy.default'
else
options[:time_format] || :'alchemy.time'
end
value = l(attribute_value, format: localization_format)
else
value = attribute_value
end
options.reverse_merge!(truncate: 50)
if options[:truncate]
value.to_s.truncate(options.fetch(:truncate, 50))
else
value
end
end | [
"def",
"render_attribute",
"(",
"resource",
",",
"attribute",
",",
"options",
"=",
"{",
"}",
")",
"attribute_value",
"=",
"resource",
".",
"send",
"(",
"attribute",
"[",
":name",
"]",
")",
"if",
"attribute",
"[",
":relation",
"]",
"record",
"=",
"resource",
".",
"send",
"(",
"attribute",
"[",
":relation",
"]",
"[",
":name",
"]",
")",
"value",
"=",
"record",
".",
"present?",
"?",
"record",
".",
"send",
"(",
"attribute",
"[",
":relation",
"]",
"[",
":attr_method",
"]",
")",
":",
"Alchemy",
".",
"t",
"(",
":not_found",
")",
"elsif",
"attribute_value",
"&&",
"attribute",
"[",
":type",
"]",
".",
"to_s",
"=~",
"/",
"/",
"localization_format",
"=",
"if",
"attribute",
"[",
":type",
"]",
"==",
":datetime",
"options",
"[",
":datetime_format",
"]",
"||",
":'",
"'",
"elsif",
"attribute",
"[",
":type",
"]",
"==",
":date",
"options",
"[",
":date_format",
"]",
"||",
":'",
"'",
"else",
"options",
"[",
":time_format",
"]",
"||",
":'",
"'",
"end",
"value",
"=",
"l",
"(",
"attribute_value",
",",
"format",
":",
"localization_format",
")",
"else",
"value",
"=",
"attribute_value",
"end",
"options",
".",
"reverse_merge!",
"(",
"truncate",
":",
"50",
")",
"if",
"options",
"[",
":truncate",
"]",
"value",
".",
"to_s",
".",
"truncate",
"(",
"options",
".",
"fetch",
"(",
":truncate",
",",
"50",
")",
")",
"else",
"value",
"end",
"end"
] | Returns the value from resource attribute
If the attribute has a relation, the related object's attribute value will be returned.
The output will be truncated after 50 chars.
Pass another number to truncate then and pass false to disable this completely.
@param [Alchemy::Resource] resource
@param [Hash] attribute
@option options [Hash] :truncate (50) The length of the value returned.
@option options [Hash] :datetime_format (alchemy.default) The format of timestamps.
@option options [Hash] :time_format (alchemy.time) The format of time values.
@return [String] | [
"Returns",
"the",
"value",
"from",
"resource",
"attribute"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/resources_helper.rb#L76-L100 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/resources_helper.rb | Alchemy.ResourcesHelper.resource_attribute_field_options | def resource_attribute_field_options(attribute)
options = {hint: resource_handler.help_text_for(attribute)}
input_type = attribute[:type].to_s
case input_type
when 'boolean'
options
when 'date', 'time', 'datetime'
date = resource_instance_variable.send(attribute[:name]) || Time.current
options.merge(
as: 'string',
input_html: {
'data-datepicker-type' => input_type,
value: date ? date.iso8601 : nil
}
)
when 'text'
options.merge(as: 'text', input_html: {rows: 4})
else
options.merge(as: 'string')
end
end | ruby | def resource_attribute_field_options(attribute)
options = {hint: resource_handler.help_text_for(attribute)}
input_type = attribute[:type].to_s
case input_type
when 'boolean'
options
when 'date', 'time', 'datetime'
date = resource_instance_variable.send(attribute[:name]) || Time.current
options.merge(
as: 'string',
input_html: {
'data-datepicker-type' => input_type,
value: date ? date.iso8601 : nil
}
)
when 'text'
options.merge(as: 'text', input_html: {rows: 4})
else
options.merge(as: 'string')
end
end | [
"def",
"resource_attribute_field_options",
"(",
"attribute",
")",
"options",
"=",
"{",
"hint",
":",
"resource_handler",
".",
"help_text_for",
"(",
"attribute",
")",
"}",
"input_type",
"=",
"attribute",
"[",
":type",
"]",
".",
"to_s",
"case",
"input_type",
"when",
"'boolean'",
"options",
"when",
"'date'",
",",
"'time'",
",",
"'datetime'",
"date",
"=",
"resource_instance_variable",
".",
"send",
"(",
"attribute",
"[",
":name",
"]",
")",
"||",
"Time",
".",
"current",
"options",
".",
"merge",
"(",
"as",
":",
"'string'",
",",
"input_html",
":",
"{",
"'data-datepicker-type'",
"=>",
"input_type",
",",
"value",
":",
"date",
"?",
"date",
".",
"iso8601",
":",
"nil",
"}",
")",
"when",
"'text'",
"options",
".",
"merge",
"(",
"as",
":",
"'text'",
",",
"input_html",
":",
"{",
"rows",
":",
"4",
"}",
")",
"else",
"options",
".",
"merge",
"(",
"as",
":",
"'string'",
")",
"end",
"end"
] | Returns a options hash for simple_form input fields. | [
"Returns",
"a",
"options",
"hash",
"for",
"simple_form",
"input",
"fields",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/resources_helper.rb#L103-L123 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/resources_helper.rb | Alchemy.ResourcesHelper.render_resources | def render_resources
render partial: resource_name, collection: resources_instance_variable
rescue ActionView::MissingTemplate
render partial: 'resource', collection: resources_instance_variable
end | ruby | def render_resources
render partial: resource_name, collection: resources_instance_variable
rescue ActionView::MissingTemplate
render partial: 'resource', collection: resources_instance_variable
end | [
"def",
"render_resources",
"render",
"partial",
":",
"resource_name",
",",
"collection",
":",
"resources_instance_variable",
"rescue",
"ActionView",
"::",
"MissingTemplate",
"render",
"partial",
":",
"'resource'",
",",
"collection",
":",
"resources_instance_variable",
"end"
] | Renders the row for a resource record in the resources table.
This helper has a nice fallback. If you create a partial for your record then this partial will be rendered.
Otherwise the default +app/views/alchemy/admin/resources/_resource.html.erb+ partial gets rendered.
== Example
For a resource named +Comment+ you can create a partial named +_comment.html.erb+
# app/views/admin/comments/_comment.html.erb
<tr>
<td><%= comment.title %></td>
<td><%= comment.body %></td>
</tr>
NOTE: Alchemy gives you a local variable named like your resource | [
"Renders",
"the",
"row",
"for",
"a",
"resource",
"record",
"in",
"the",
"resources",
"table",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/resources_helper.rb#L171-L175 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/resource.rb | Alchemy.Resource.searchable_attribute_names | def searchable_attribute_names
if model.respond_to?(:searchable_alchemy_resource_attributes)
model.searchable_alchemy_resource_attributes
else
attributes.select { |a| searchable_attribute?(a) }
.concat(searchable_relation_attributes(attributes))
.collect { |h| h[:name] }
end
end | ruby | def searchable_attribute_names
if model.respond_to?(:searchable_alchemy_resource_attributes)
model.searchable_alchemy_resource_attributes
else
attributes.select { |a| searchable_attribute?(a) }
.concat(searchable_relation_attributes(attributes))
.collect { |h| h[:name] }
end
end | [
"def",
"searchable_attribute_names",
"if",
"model",
".",
"respond_to?",
"(",
":searchable_alchemy_resource_attributes",
")",
"model",
".",
"searchable_alchemy_resource_attributes",
"else",
"attributes",
".",
"select",
"{",
"|",
"a",
"|",
"searchable_attribute?",
"(",
"a",
")",
"}",
".",
"concat",
"(",
"searchable_relation_attributes",
"(",
"attributes",
")",
")",
".",
"collect",
"{",
"|",
"h",
"|",
"h",
"[",
":name",
"]",
"}",
"end",
"end"
] | Returns all attribute names that are searchable in the admin interface | [
"Returns",
"all",
"attribute",
"names",
"that",
"are",
"searchable",
"in",
"the",
"admin",
"interface"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/resource.rb#L177-L185 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/resource.rb | Alchemy.Resource.help_text_for | def help_text_for(attribute)
::I18n.translate!(attribute[:name], scope: [:alchemy, :resource_help_texts, resource_name])
rescue ::I18n::MissingTranslationData
false
end | ruby | def help_text_for(attribute)
::I18n.translate!(attribute[:name], scope: [:alchemy, :resource_help_texts, resource_name])
rescue ::I18n::MissingTranslationData
false
end | [
"def",
"help_text_for",
"(",
"attribute",
")",
"::",
"I18n",
".",
"translate!",
"(",
"attribute",
"[",
":name",
"]",
",",
"scope",
":",
"[",
":alchemy",
",",
":resource_help_texts",
",",
"resource_name",
"]",
")",
"rescue",
"::",
"I18n",
"::",
"MissingTranslationData",
"false",
"end"
] | Returns a help text for resource's form
=== Example:
de:
alchemy:
resource_help_texts:
my_resource_name:
attribute_name: This is the fancy help text | [
"Returns",
"a",
"help",
"text",
"for",
"resource",
"s",
"form"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/resource.rb#L213-L217 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/resource.rb | Alchemy.Resource.map_relations | def map_relations
self.resource_relations = {}
model.alchemy_resource_relations.each do |name, options|
name = name.to_s.gsub(/_id$/, '') # ensure that we don't have an id
association = association_from_relation_name(name)
foreign_key = association.options[:foreign_key] || "#{association.name}_id".to_sym
resource_relations[foreign_key] = options.merge(model_association: association, name: name)
end
end | ruby | def map_relations
self.resource_relations = {}
model.alchemy_resource_relations.each do |name, options|
name = name.to_s.gsub(/_id$/, '') # ensure that we don't have an id
association = association_from_relation_name(name)
foreign_key = association.options[:foreign_key] || "#{association.name}_id".to_sym
resource_relations[foreign_key] = options.merge(model_association: association, name: name)
end
end | [
"def",
"map_relations",
"self",
".",
"resource_relations",
"=",
"{",
"}",
"model",
".",
"alchemy_resource_relations",
".",
"each",
"do",
"|",
"name",
",",
"options",
"|",
"name",
"=",
"name",
".",
"to_s",
".",
"gsub",
"(",
"/",
"/",
",",
"''",
")",
"# ensure that we don't have an id",
"association",
"=",
"association_from_relation_name",
"(",
"name",
")",
"foreign_key",
"=",
"association",
".",
"options",
"[",
":foreign_key",
"]",
"||",
"\"#{association.name}_id\"",
".",
"to_sym",
"resource_relations",
"[",
"foreign_key",
"]",
"=",
"options",
".",
"merge",
"(",
"model_association",
":",
"association",
",",
"name",
":",
"name",
")",
"end",
"end"
] | Expands the resource_relations hash with matching activerecord associations data. | [
"Expands",
"the",
"resource_relations",
"hash",
"with",
"matching",
"activerecord",
"associations",
"data",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/resource.rb#L286-L294 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/resource.rb | Alchemy.Resource.store_model_associations | def store_model_associations
self.model_associations = model.reflect_on_all_associations.delete_if { |a| DEFAULT_SKIPPED_ASSOCIATIONS.include?(a.name.to_s) }
end | ruby | def store_model_associations
self.model_associations = model.reflect_on_all_associations.delete_if { |a| DEFAULT_SKIPPED_ASSOCIATIONS.include?(a.name.to_s) }
end | [
"def",
"store_model_associations",
"self",
".",
"model_associations",
"=",
"model",
".",
"reflect_on_all_associations",
".",
"delete_if",
"{",
"|",
"a",
"|",
"DEFAULT_SKIPPED_ASSOCIATIONS",
".",
"include?",
"(",
"a",
".",
"name",
".",
"to_s",
")",
"}",
"end"
] | Stores all activerecord associations in model_associations attribute | [
"Stores",
"all",
"activerecord",
"associations",
"in",
"model_associations",
"attribute"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/resource.rb#L297-L299 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/shell.rb | Alchemy.Shell.display_todos | def display_todos
return if todos.empty?
log "\n+---------+", :message
log "| 📝 TODO |", :message
log "+---------+\n", :message
puts "\nWe did most of the work for you, but there are still some things left for you to do."
todos.each_with_index do |todo, i|
title = "\n#{i + 1}. #{todo[0]}"
log title, :message
puts '=' * title.length
puts ""
log todo[1], :message
end
puts ""
puts "============================================================"
puts "= ✨ Please take a minute and read the notes from above ✨ ="
puts "============================================================"
puts ""
end | ruby | def display_todos
return if todos.empty?
log "\n+---------+", :message
log "| 📝 TODO |", :message
log "+---------+\n", :message
puts "\nWe did most of the work for you, but there are still some things left for you to do."
todos.each_with_index do |todo, i|
title = "\n#{i + 1}. #{todo[0]}"
log title, :message
puts '=' * title.length
puts ""
log todo[1], :message
end
puts ""
puts "============================================================"
puts "= ✨ Please take a minute and read the notes from above ✨ ="
puts "============================================================"
puts ""
end | [
"def",
"display_todos",
"return",
"if",
"todos",
".",
"empty?",
"log",
"\"\\n+---------+\"",
",",
":message",
"log",
"\"| 📝 TODO |\", :",
"m",
"ssage",
"log",
"\"+---------+\\n\"",
",",
":message",
"puts",
"\"\\nWe did most of the work for you, but there are still some things left for you to do.\"",
"todos",
".",
"each_with_index",
"do",
"|",
"todo",
",",
"i",
"|",
"title",
"=",
"\"\\n#{i + 1}. #{todo[0]}\"",
"log",
"title",
",",
":message",
"puts",
"'='",
"*",
"title",
".",
"length",
"puts",
"\"\"",
"log",
"todo",
"[",
"1",
"]",
",",
":message",
"end",
"puts",
"\"\"",
"puts",
"\"============================================================\"",
"puts",
"\"= ✨ Please take a minute and read the notes from above ✨ =\"",
"puts",
"\"============================================================\"",
"puts",
"\"\"",
"end"
] | Prints out all the todos | [
"Prints",
"out",
"all",
"the",
"todos"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/shell.rb#L49-L68 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/shell.rb | Alchemy.Shell.log | def log(message, type = nil)
unless Alchemy::Shell.silenced?
case type
when :skip
puts "#{color(:yellow)}== Skipping! #{message}#{color(:clear)}"
when :error
puts "#{color(:red)}!! ERROR: #{message}#{color(:clear)}"
when :message
puts "#{color(:clear)}#{message}"
else
puts "#{color(:green)}== #{message}#{color(:clear)}"
end
end
end | ruby | def log(message, type = nil)
unless Alchemy::Shell.silenced?
case type
when :skip
puts "#{color(:yellow)}== Skipping! #{message}#{color(:clear)}"
when :error
puts "#{color(:red)}!! ERROR: #{message}#{color(:clear)}"
when :message
puts "#{color(:clear)}#{message}"
else
puts "#{color(:green)}== #{message}#{color(:clear)}"
end
end
end | [
"def",
"log",
"(",
"message",
",",
"type",
"=",
"nil",
")",
"unless",
"Alchemy",
"::",
"Shell",
".",
"silenced?",
"case",
"type",
"when",
":skip",
"puts",
"\"#{color(:yellow)}== Skipping! #{message}#{color(:clear)}\"",
"when",
":error",
"puts",
"\"#{color(:red)}!! ERROR: #{message}#{color(:clear)}\"",
"when",
":message",
"puts",
"\"#{color(:clear)}#{message}\"",
"else",
"puts",
"\"#{color(:green)}== #{message}#{color(:clear)}\"",
"end",
"end",
"end"
] | Prints out the given log message with the color due to its type
@param [String] message
@param [Symbol] type | [
"Prints",
"out",
"the",
"given",
"log",
"message",
"with",
"the",
"color",
"due",
"to",
"its",
"type"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/shell.rb#L75-L88 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/shell.rb | Alchemy.Shell.color | def color(name)
color_const = name.to_s.upcase
if Thor::Shell::Color.const_defined?(color_const)
"Thor::Shell::Color::#{color_const}".constantize
else
""
end
end | ruby | def color(name)
color_const = name.to_s.upcase
if Thor::Shell::Color.const_defined?(color_const)
"Thor::Shell::Color::#{color_const}".constantize
else
""
end
end | [
"def",
"color",
"(",
"name",
")",
"color_const",
"=",
"name",
".",
"to_s",
".",
"upcase",
"if",
"Thor",
"::",
"Shell",
"::",
"Color",
".",
"const_defined?",
"(",
"color_const",
")",
"\"Thor::Shell::Color::#{color_const}\"",
".",
"constantize",
"else",
"\"\"",
"end",
"end"
] | Gives the color string using Thor
Used for colorizing the message on the shell
@param [String] name
@return [String] | [
"Gives",
"the",
"color",
"string",
"using",
"Thor",
"Used",
"for",
"colorizing",
"the",
"message",
"on",
"the",
"shell"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/shell.rb#L98-L105 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/essence_picture.rb | Alchemy.EssencePicture.picture_url_options | def picture_url_options
return {} if picture.nil?
{
format: picture.default_render_format,
crop_from: crop_from.presence,
crop_size: crop_size.presence
}.with_indifferent_access
end | ruby | def picture_url_options
return {} if picture.nil?
{
format: picture.default_render_format,
crop_from: crop_from.presence,
crop_size: crop_size.presence
}.with_indifferent_access
end | [
"def",
"picture_url_options",
"return",
"{",
"}",
"if",
"picture",
".",
"nil?",
"{",
"format",
":",
"picture",
".",
"default_render_format",
",",
"crop_from",
":",
"crop_from",
".",
"presence",
",",
"crop_size",
":",
"crop_size",
".",
"presence",
"}",
".",
"with_indifferent_access",
"end"
] | Picture rendering options
Returns the +default_render_format+ of the associated +Alchemy::Picture+
together with the +crop_from+ and +crop_size+ values
@return [HashWithIndifferentAccess] | [
"Picture",
"rendering",
"options"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/essence_picture.rb#L72-L80 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/essence_picture.rb | Alchemy.EssencePicture.thumbnail_url | def thumbnail_url(options = {})
return if picture.nil?
crop = crop_values_present? || content.settings_value(:crop, options)
size = render_size || content.settings_value(:size, options)
options = {
size: thumbnail_size(size, crop),
crop: !!crop,
crop_from: crop_from.presence,
crop_size: crop_size.presence,
flatten: true,
format: picture.image_file_format
}
picture.url(options)
end | ruby | def thumbnail_url(options = {})
return if picture.nil?
crop = crop_values_present? || content.settings_value(:crop, options)
size = render_size || content.settings_value(:size, options)
options = {
size: thumbnail_size(size, crop),
crop: !!crop,
crop_from: crop_from.presence,
crop_size: crop_size.presence,
flatten: true,
format: picture.image_file_format
}
picture.url(options)
end | [
"def",
"thumbnail_url",
"(",
"options",
"=",
"{",
"}",
")",
"return",
"if",
"picture",
".",
"nil?",
"crop",
"=",
"crop_values_present?",
"||",
"content",
".",
"settings_value",
"(",
":crop",
",",
"options",
")",
"size",
"=",
"render_size",
"||",
"content",
".",
"settings_value",
"(",
":size",
",",
"options",
")",
"options",
"=",
"{",
"size",
":",
"thumbnail_size",
"(",
"size",
",",
"crop",
")",
",",
"crop",
":",
"!",
"!",
"crop",
",",
"crop_from",
":",
"crop_from",
".",
"presence",
",",
"crop_size",
":",
"crop_size",
".",
"presence",
",",
"flatten",
":",
"true",
",",
"format",
":",
"picture",
".",
"image_file_format",
"}",
"picture",
".",
"url",
"(",
"options",
")",
"end"
] | Returns an url for the thumbnail representation of the assigned picture
It takes cropping values into account, so it always represents the current
image displayed in the frontend.
@return [String] | [
"Returns",
"an",
"url",
"for",
"the",
"thumbnail",
"representation",
"of",
"the",
"assigned",
"picture"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/essence_picture.rb#L88-L104 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/essence_picture.rb | Alchemy.EssencePicture.cropping_mask | def cropping_mask
return if crop_from.blank? || crop_size.blank?
crop_from = point_from_string(read_attribute(:crop_from))
crop_size = sizes_from_string(read_attribute(:crop_size))
point_and_mask_to_points(crop_from, crop_size)
end | ruby | def cropping_mask
return if crop_from.blank? || crop_size.blank?
crop_from = point_from_string(read_attribute(:crop_from))
crop_size = sizes_from_string(read_attribute(:crop_size))
point_and_mask_to_points(crop_from, crop_size)
end | [
"def",
"cropping_mask",
"return",
"if",
"crop_from",
".",
"blank?",
"||",
"crop_size",
".",
"blank?",
"crop_from",
"=",
"point_from_string",
"(",
"read_attribute",
"(",
":crop_from",
")",
")",
"crop_size",
"=",
"sizes_from_string",
"(",
"read_attribute",
"(",
":crop_size",
")",
")",
"point_and_mask_to_points",
"(",
"crop_from",
",",
"crop_size",
")",
"end"
] | A Hash of coordinates suitable for the graphical image cropper.
@return [Hash] | [
"A",
"Hash",
"of",
"coordinates",
"suitable",
"for",
"the",
"graphical",
"image",
"cropper",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/essence_picture.rb#L120-L126 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/essence_picture.rb | Alchemy.EssencePicture.allow_image_cropping? | def allow_image_cropping?(options = {})
content && content.settings_value(:crop, options) && picture &&
picture.can_be_cropped_to(
content.settings_value(:size, options),
content.settings_value(:upsample, options)
)
end | ruby | def allow_image_cropping?(options = {})
content && content.settings_value(:crop, options) && picture &&
picture.can_be_cropped_to(
content.settings_value(:size, options),
content.settings_value(:upsample, options)
)
end | [
"def",
"allow_image_cropping?",
"(",
"options",
"=",
"{",
"}",
")",
"content",
"&&",
"content",
".",
"settings_value",
"(",
":crop",
",",
"options",
")",
"&&",
"picture",
"&&",
"picture",
".",
"can_be_cropped_to",
"(",
"content",
".",
"settings_value",
"(",
":size",
",",
"options",
")",
",",
"content",
".",
"settings_value",
"(",
":upsample",
",",
"options",
")",
")",
"end"
] | Show image cropping link for content and options? | [
"Show",
"image",
"cropping",
"link",
"for",
"content",
"and",
"options?"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/essence_picture.rb#L136-L142 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/hints.rb | Alchemy.Hints.hint | def hint
hint = definition['hint']
if hint == true
Alchemy.t(name, scope: hint_translation_scope)
else
hint
end
end | ruby | def hint
hint = definition['hint']
if hint == true
Alchemy.t(name, scope: hint_translation_scope)
else
hint
end
end | [
"def",
"hint",
"hint",
"=",
"definition",
"[",
"'hint'",
"]",
"if",
"hint",
"==",
"true",
"Alchemy",
".",
"t",
"(",
"name",
",",
"scope",
":",
"hint_translation_scope",
")",
"else",
"hint",
"end",
"end"
] | Returns a hint
To add a hint to a content pass +hint: true+ to the element definition in its element.yml
Then the hint itself is placed in the locale yml files.
Alternativly you can pass the hint itself to the hint key.
== Locale Example:
# elements.yml
- name: headline
contents:
- name: headline
type: EssenceText
hint: true
# config/locales/de.yml
de:
content_hints:
headline: Lorem ipsum
== Hint Key Example:
- name: headline
contents:
- name: headline
type: EssenceText
hint: Lorem ipsum
@return String | [
"Returns",
"a",
"hint"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/hints.rb#L37-L44 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/picture/transformations.rb | Alchemy.Picture::Transformations.default_mask | def default_mask(mask_arg)
mask = mask_arg.dup
mask[:width] = image_file_width if mask[:width].zero?
mask[:height] = image_file_height if mask[:height].zero?
crop_size = size_when_fitting({width: image_file_width, height: image_file_height}, mask)
top_left = get_top_left_crop_corner(crop_size)
point_and_mask_to_points(top_left, crop_size)
end | ruby | def default_mask(mask_arg)
mask = mask_arg.dup
mask[:width] = image_file_width if mask[:width].zero?
mask[:height] = image_file_height if mask[:height].zero?
crop_size = size_when_fitting({width: image_file_width, height: image_file_height}, mask)
top_left = get_top_left_crop_corner(crop_size)
point_and_mask_to_points(top_left, crop_size)
end | [
"def",
"default_mask",
"(",
"mask_arg",
")",
"mask",
"=",
"mask_arg",
".",
"dup",
"mask",
"[",
":width",
"]",
"=",
"image_file_width",
"if",
"mask",
"[",
":width",
"]",
".",
"zero?",
"mask",
"[",
":height",
"]",
"=",
"image_file_height",
"if",
"mask",
"[",
":height",
"]",
".",
"zero?",
"crop_size",
"=",
"size_when_fitting",
"(",
"{",
"width",
":",
"image_file_width",
",",
"height",
":",
"image_file_height",
"}",
",",
"mask",
")",
"top_left",
"=",
"get_top_left_crop_corner",
"(",
"crop_size",
")",
"point_and_mask_to_points",
"(",
"top_left",
",",
"crop_size",
")",
"end"
] | Returns the default centered image mask for a given size.
If the mask is bigger than the image, the mask is scaled down
so the largest possible part of the image is visible. | [
"Returns",
"the",
"default",
"centered",
"image",
"mask",
"for",
"a",
"given",
"size",
".",
"If",
"the",
"mask",
"is",
"bigger",
"than",
"the",
"image",
"the",
"mask",
"is",
"scaled",
"down",
"so",
"the",
"largest",
"possible",
"part",
"of",
"the",
"image",
"is",
"visible",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/picture/transformations.rb#L17-L26 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/picture/transformations.rb | Alchemy.Picture::Transformations.thumbnail_size | def thumbnail_size(size_string = "0x0", crop = false)
size = sizes_from_string(size_string)
# only if crop is set do we need to actually parse the size string, otherwise
# we take the base image size.
if crop
size[:width] = get_base_dimensions[:width] if size[:width].zero?
size[:height] = get_base_dimensions[:height] if size[:height].zero?
size = reduce_to_image(size)
else
size = get_base_dimensions
end
size = size_when_fitting({width: THUMBNAIL_WIDTH, height: THUMBNAIL_HEIGHT}, size)
"#{size[:width]}x#{size[:height]}"
end | ruby | def thumbnail_size(size_string = "0x0", crop = false)
size = sizes_from_string(size_string)
# only if crop is set do we need to actually parse the size string, otherwise
# we take the base image size.
if crop
size[:width] = get_base_dimensions[:width] if size[:width].zero?
size[:height] = get_base_dimensions[:height] if size[:height].zero?
size = reduce_to_image(size)
else
size = get_base_dimensions
end
size = size_when_fitting({width: THUMBNAIL_WIDTH, height: THUMBNAIL_HEIGHT}, size)
"#{size[:width]}x#{size[:height]}"
end | [
"def",
"thumbnail_size",
"(",
"size_string",
"=",
"\"0x0\"",
",",
"crop",
"=",
"false",
")",
"size",
"=",
"sizes_from_string",
"(",
"size_string",
")",
"# only if crop is set do we need to actually parse the size string, otherwise",
"# we take the base image size.",
"if",
"crop",
"size",
"[",
":width",
"]",
"=",
"get_base_dimensions",
"[",
":width",
"]",
"if",
"size",
"[",
":width",
"]",
".",
"zero?",
"size",
"[",
":height",
"]",
"=",
"get_base_dimensions",
"[",
":height",
"]",
"if",
"size",
"[",
":height",
"]",
".",
"zero?",
"size",
"=",
"reduce_to_image",
"(",
"size",
")",
"else",
"size",
"=",
"get_base_dimensions",
"end",
"size",
"=",
"size_when_fitting",
"(",
"{",
"width",
":",
"THUMBNAIL_WIDTH",
",",
"height",
":",
"THUMBNAIL_HEIGHT",
"}",
",",
"size",
")",
"\"#{size[:width]}x#{size[:height]}\"",
"end"
] | Returns a size value String for the thumbnail used in essence picture editors. | [
"Returns",
"a",
"size",
"value",
"String",
"for",
"the",
"thumbnail",
"used",
"in",
"essence",
"picture",
"editors",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/picture/transformations.rb#L30-L45 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/picture/transformations.rb | Alchemy.Picture::Transformations.crop | def crop(size, crop_from = nil, crop_size = nil, upsample = false)
raise "No size given!" if size.empty?
render_to = sizes_from_string(size)
if crop_from && crop_size
top_left = point_from_string(crop_from)
crop_dimensions = sizes_from_string(crop_size)
xy_crop_resize(render_to, top_left, crop_dimensions, upsample)
else
center_crop(render_to, upsample)
end
end | ruby | def crop(size, crop_from = nil, crop_size = nil, upsample = false)
raise "No size given!" if size.empty?
render_to = sizes_from_string(size)
if crop_from && crop_size
top_left = point_from_string(crop_from)
crop_dimensions = sizes_from_string(crop_size)
xy_crop_resize(render_to, top_left, crop_dimensions, upsample)
else
center_crop(render_to, upsample)
end
end | [
"def",
"crop",
"(",
"size",
",",
"crop_from",
"=",
"nil",
",",
"crop_size",
"=",
"nil",
",",
"upsample",
"=",
"false",
")",
"raise",
"\"No size given!\"",
"if",
"size",
".",
"empty?",
"render_to",
"=",
"sizes_from_string",
"(",
"size",
")",
"if",
"crop_from",
"&&",
"crop_size",
"top_left",
"=",
"point_from_string",
"(",
"crop_from",
")",
"crop_dimensions",
"=",
"sizes_from_string",
"(",
"crop_size",
")",
"xy_crop_resize",
"(",
"render_to",
",",
"top_left",
",",
"crop_dimensions",
",",
"upsample",
")",
"else",
"center_crop",
"(",
"render_to",
",",
"upsample",
")",
"end",
"end"
] | Returns the rendered cropped image. Tries to use the crop_from and crop_size
parameters. When they can't be parsed, it just crops from the center. | [
"Returns",
"the",
"rendered",
"cropped",
"image",
".",
"Tries",
"to",
"use",
"the",
"crop_from",
"and",
"crop_size",
"parameters",
".",
"When",
"they",
"can",
"t",
"be",
"parsed",
"it",
"just",
"crops",
"from",
"the",
"center",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/picture/transformations.rb#L50-L60 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/picture/transformations.rb | Alchemy.Picture::Transformations.size_when_fitting | def size_when_fitting(target, dimensions = get_base_dimensions)
zoom = [
dimensions[:width].to_f / target[:width],
dimensions[:height].to_f / target[:height]
].max
if zoom == 0.0
width = target[:width]
height = target[:height]
else
width = (dimensions[:width] / zoom).round
height = (dimensions[:height] / zoom).round
end
{width: width.to_i, height: height.to_i}
end | ruby | def size_when_fitting(target, dimensions = get_base_dimensions)
zoom = [
dimensions[:width].to_f / target[:width],
dimensions[:height].to_f / target[:height]
].max
if zoom == 0.0
width = target[:width]
height = target[:height]
else
width = (dimensions[:width] / zoom).round
height = (dimensions[:height] / zoom).round
end
{width: width.to_i, height: height.to_i}
end | [
"def",
"size_when_fitting",
"(",
"target",
",",
"dimensions",
"=",
"get_base_dimensions",
")",
"zoom",
"=",
"[",
"dimensions",
"[",
":width",
"]",
".",
"to_f",
"/",
"target",
"[",
":width",
"]",
",",
"dimensions",
"[",
":height",
"]",
".",
"to_f",
"/",
"target",
"[",
":height",
"]",
"]",
".",
"max",
"if",
"zoom",
"==",
"0.0",
"width",
"=",
"target",
"[",
":width",
"]",
"height",
"=",
"target",
"[",
":height",
"]",
"else",
"width",
"=",
"(",
"dimensions",
"[",
":width",
"]",
"/",
"zoom",
")",
".",
"round",
"height",
"=",
"(",
"dimensions",
"[",
":height",
"]",
"/",
"zoom",
")",
".",
"round",
"end",
"{",
"width",
":",
"width",
".",
"to_i",
",",
"height",
":",
"height",
".",
"to_i",
"}",
"end"
] | This function takes a target and a base dimensions hash and returns
the dimensions of the image when the base dimensions hash fills
the target.
Aspect ratio will be preserved. | [
"This",
"function",
"takes",
"a",
"target",
"and",
"a",
"base",
"dimensions",
"hash",
"and",
"returns",
"the",
"dimensions",
"of",
"the",
"image",
"when",
"the",
"base",
"dimensions",
"hash",
"fills",
"the",
"target",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/picture/transformations.rb#L182-L197 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/picture/transformations.rb | Alchemy.Picture::Transformations.center_crop | def center_crop(dimensions, upsample)
if is_smaller_than(dimensions) && upsample == false
dimensions = reduce_to_image(dimensions)
end
image_file.thumb("#{dimensions_to_string(dimensions)}#")
end | ruby | def center_crop(dimensions, upsample)
if is_smaller_than(dimensions) && upsample == false
dimensions = reduce_to_image(dimensions)
end
image_file.thumb("#{dimensions_to_string(dimensions)}#")
end | [
"def",
"center_crop",
"(",
"dimensions",
",",
"upsample",
")",
"if",
"is_smaller_than",
"(",
"dimensions",
")",
"&&",
"upsample",
"==",
"false",
"dimensions",
"=",
"reduce_to_image",
"(",
"dimensions",
")",
"end",
"image_file",
".",
"thumb",
"(",
"\"#{dimensions_to_string(dimensions)}#\"",
")",
"end"
] | Uses imagemagick to make a centercropped thumbnail. Does not scale the image up. | [
"Uses",
"imagemagick",
"to",
"make",
"a",
"centercropped",
"thumbnail",
".",
"Does",
"not",
"scale",
"the",
"image",
"up",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/picture/transformations.rb#L232-L237 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/picture/transformations.rb | Alchemy.Picture::Transformations.xy_crop_resize | def xy_crop_resize(dimensions, top_left, crop_dimensions, upsample)
crop_argument = "-crop #{dimensions_to_string(crop_dimensions)}"
crop_argument += "+#{top_left[:x]}+#{top_left[:y]}"
resize_argument = "-resize #{dimensions_to_string(dimensions)}"
resize_argument += ">" unless upsample
image_file.convert "#{crop_argument} #{resize_argument}"
end | ruby | def xy_crop_resize(dimensions, top_left, crop_dimensions, upsample)
crop_argument = "-crop #{dimensions_to_string(crop_dimensions)}"
crop_argument += "+#{top_left[:x]}+#{top_left[:y]}"
resize_argument = "-resize #{dimensions_to_string(dimensions)}"
resize_argument += ">" unless upsample
image_file.convert "#{crop_argument} #{resize_argument}"
end | [
"def",
"xy_crop_resize",
"(",
"dimensions",
",",
"top_left",
",",
"crop_dimensions",
",",
"upsample",
")",
"crop_argument",
"=",
"\"-crop #{dimensions_to_string(crop_dimensions)}\"",
"crop_argument",
"+=",
"\"+#{top_left[:x]}+#{top_left[:y]}\"",
"resize_argument",
"=",
"\"-resize #{dimensions_to_string(dimensions)}\"",
"resize_argument",
"+=",
"\">\"",
"unless",
"upsample",
"image_file",
".",
"convert",
"\"#{crop_argument} #{resize_argument}\"",
"end"
] | Use imagemagick to custom crop an image. Uses -thumbnail for better performance when resizing. | [
"Use",
"imagemagick",
"to",
"custom",
"crop",
"an",
"image",
".",
"Uses",
"-",
"thumbnail",
"for",
"better",
"performance",
"when",
"resizing",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/picture/transformations.rb#L241-L248 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/picture/transformations.rb | Alchemy.Picture::Transformations.reduce_to_image | def reduce_to_image(dimensions)
{
width: [dimensions[:width], image_file_width].min,
height: [dimensions[:height], image_file_height].min
}
end | ruby | def reduce_to_image(dimensions)
{
width: [dimensions[:width], image_file_width].min,
height: [dimensions[:height], image_file_height].min
}
end | [
"def",
"reduce_to_image",
"(",
"dimensions",
")",
"{",
"width",
":",
"[",
"dimensions",
"[",
":width",
"]",
",",
"image_file_width",
"]",
".",
"min",
",",
"height",
":",
"[",
"dimensions",
"[",
":height",
"]",
",",
"image_file_height",
"]",
".",
"min",
"}",
"end"
] | Used when centercropping. | [
"Used",
"when",
"centercropping",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/picture/transformations.rb#L252-L257 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/page.rb | Alchemy.Page.previous | def previous(options = {})
pages = self_and_siblings.where('lft < ?', lft)
select_page(pages, options.merge(order: :desc))
end | ruby | def previous(options = {})
pages = self_and_siblings.where('lft < ?', lft)
select_page(pages, options.merge(order: :desc))
end | [
"def",
"previous",
"(",
"options",
"=",
"{",
"}",
")",
"pages",
"=",
"self_and_siblings",
".",
"where",
"(",
"'lft < ?'",
",",
"lft",
")",
"select_page",
"(",
"pages",
",",
"options",
".",
"merge",
"(",
"order",
":",
":desc",
")",
")",
"end"
] | Returns the previous page on the same level or nil.
@option options [Boolean] :restricted (false)
only restricted pages (true), skip restricted pages (false)
@option options [Boolean] :public (true)
only public pages (true), skip public pages (false) | [
"Returns",
"the",
"previous",
"page",
"on",
"the",
"same",
"level",
"or",
"nil",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/page.rb#L349-L352 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/page.rb | Alchemy.Page.publish! | def publish!
current_time = Time.current
update_columns(
published_at: current_time,
public_on: already_public_for?(current_time) ? public_on : current_time,
public_until: still_public_for?(current_time) ? public_until : nil
)
end | ruby | def publish!
current_time = Time.current
update_columns(
published_at: current_time,
public_on: already_public_for?(current_time) ? public_on : current_time,
public_until: still_public_for?(current_time) ? public_until : nil
)
end | [
"def",
"publish!",
"current_time",
"=",
"Time",
".",
"current",
"update_columns",
"(",
"published_at",
":",
"current_time",
",",
"public_on",
":",
"already_public_for?",
"(",
"current_time",
")",
"?",
"public_on",
":",
"current_time",
",",
"public_until",
":",
"still_public_for?",
"(",
"current_time",
")",
"?",
"public_until",
":",
"nil",
")",
"end"
] | Publishes the page.
Sets +public_on+ and the +published_at+ value to current time
and resets +public_until+ to nil
The +published_at+ attribute is used as +cache_key+. | [
"Publishes",
"the",
"page",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/page.rb#L427-L434 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/page.rb | Alchemy.Page.create_legacy_url | def create_legacy_url
if active_record_5_1?
former_urlname = urlname_before_last_save
else
former_urlname = urlname_was
end
legacy_urls.find_or_create_by(urlname: former_urlname)
end | ruby | def create_legacy_url
if active_record_5_1?
former_urlname = urlname_before_last_save
else
former_urlname = urlname_was
end
legacy_urls.find_or_create_by(urlname: former_urlname)
end | [
"def",
"create_legacy_url",
"if",
"active_record_5_1?",
"former_urlname",
"=",
"urlname_before_last_save",
"else",
"former_urlname",
"=",
"urlname_was",
"end",
"legacy_urls",
".",
"find_or_create_by",
"(",
"urlname",
":",
"former_urlname",
")",
"end"
] | Stores the old urlname in a LegacyPageUrl | [
"Stores",
"the",
"old",
"urlname",
"in",
"a",
"LegacyPageUrl"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/page.rb#L524-L531 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/page/page_natures.rb | Alchemy.Page::PageNatures.cache_page? | def cache_page?
return false unless caching_enabled?
page_layout = PageLayout.get(self.page_layout)
page_layout['cache'] != false && page_layout['searchresults'] != true
end | ruby | def cache_page?
return false unless caching_enabled?
page_layout = PageLayout.get(self.page_layout)
page_layout['cache'] != false && page_layout['searchresults'] != true
end | [
"def",
"cache_page?",
"return",
"false",
"unless",
"caching_enabled?",
"page_layout",
"=",
"PageLayout",
".",
"get",
"(",
"self",
".",
"page_layout",
")",
"page_layout",
"[",
"'cache'",
"]",
"!=",
"false",
"&&",
"page_layout",
"[",
"'searchresults'",
"]",
"!=",
"true",
"end"
] | Returns true if the page cache control headers should be set.
== Disable Alchemy's page caching globally
# config/alchemy/config.yml
...
cache_pages: false
== Disable caching on page layout level
# config/alchemy/page_layouts.yml
- name: contact
cache: false
== Note:
This only sets the cache control headers and skips rendering of the page body,
if the cache is fresh.
This does not disable the fragment caching in the views.
So if you don't want a page and it's elements to be cached,
then be sure to not use <% cache element %> in the views.
@returns Boolean | [
"Returns",
"true",
"if",
"the",
"page",
"cache",
"control",
"headers",
"should",
"be",
"set",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/page/page_natures.rb#L169-L173 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/taggable.rb | Alchemy.Taggable.tag_list= | def tag_list=(tags)
case tags
when String
self.tag_names = tags.split(/,\s*/)
when Array
self.tag_names = tags
end
end | ruby | def tag_list=(tags)
case tags
when String
self.tag_names = tags.split(/,\s*/)
when Array
self.tag_names = tags
end
end | [
"def",
"tag_list",
"=",
"(",
"tags",
")",
"case",
"tags",
"when",
"String",
"self",
".",
"tag_names",
"=",
"tags",
".",
"split",
"(",
"/",
"\\s",
"/",
")",
"when",
"Array",
"self",
".",
"tag_names",
"=",
"tags",
"end",
"end"
] | Set a list of tags
Pass a String with comma separated tag names or
an Array of tag names | [
"Set",
"a",
"list",
"of",
"tags",
"Pass",
"a",
"String",
"with",
"comma",
"separated",
"tag",
"names",
"or",
"an",
"Array",
"of",
"tag",
"names"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/taggable.rb#L14-L21 | train |
AlchemyCMS/alchemy_cms | app/controllers/alchemy/attachments_controller.rb | Alchemy.AttachmentsController.download | def download
response.headers['Content-Length'] = @attachment.file.size.to_s
send_file(
@attachment.file.path, {
filename: @attachment.file_name,
type: @attachment.file_mime_type
}
)
end | ruby | def download
response.headers['Content-Length'] = @attachment.file.size.to_s
send_file(
@attachment.file.path, {
filename: @attachment.file_name,
type: @attachment.file_mime_type
}
)
end | [
"def",
"download",
"response",
".",
"headers",
"[",
"'Content-Length'",
"]",
"=",
"@attachment",
".",
"file",
".",
"size",
".",
"to_s",
"send_file",
"(",
"@attachment",
".",
"file",
".",
"path",
",",
"{",
"filename",
":",
"@attachment",
".",
"file_name",
",",
"type",
":",
"@attachment",
".",
"file_mime_type",
"}",
")",
"end"
] | sends file as attachment. aka download | [
"sends",
"file",
"as",
"attachment",
".",
"aka",
"download"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/alchemy/attachments_controller.rb#L22-L30 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/picture.rb | Alchemy.Picture.security_token | def security_token(params = {})
params = params.dup.stringify_keys
params.update({
'crop' => params['crop'] ? 'crop' : nil,
'id' => id
})
PictureAttributes.secure(params)
end | ruby | def security_token(params = {})
params = params.dup.stringify_keys
params.update({
'crop' => params['crop'] ? 'crop' : nil,
'id' => id
})
PictureAttributes.secure(params)
end | [
"def",
"security_token",
"(",
"params",
"=",
"{",
"}",
")",
"params",
"=",
"params",
".",
"dup",
".",
"stringify_keys",
"params",
".",
"update",
"(",
"{",
"'crop'",
"=>",
"params",
"[",
"'crop'",
"]",
"?",
"'crop'",
":",
"nil",
",",
"'id'",
"=>",
"id",
"}",
")",
"PictureAttributes",
".",
"secure",
"(",
"params",
")",
"end"
] | Returns a security token for signed picture rendering requests.
Pass a params hash containing:
size [String] (Optional)
crop [Boolean] (Optional)
crop_from [String] (Optional)
crop_size [String] (Optional)
quality [Integer] (Optional)
to sign them. | [
"Returns",
"a",
"security",
"token",
"for",
"signed",
"picture",
"rendering",
"requests",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/picture.rb#L262-L269 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/page/page_naming.rb | Alchemy.Page::PageNaming.update_urlname! | def update_urlname!
new_urlname = nested_url_name(slug)
if urlname != new_urlname
legacy_urls.create(urlname: urlname)
update_column(:urlname, new_urlname)
end
end | ruby | def update_urlname!
new_urlname = nested_url_name(slug)
if urlname != new_urlname
legacy_urls.create(urlname: urlname)
update_column(:urlname, new_urlname)
end
end | [
"def",
"update_urlname!",
"new_urlname",
"=",
"nested_url_name",
"(",
"slug",
")",
"if",
"urlname",
"!=",
"new_urlname",
"legacy_urls",
".",
"create",
"(",
"urlname",
":",
"urlname",
")",
"update_column",
"(",
":urlname",
",",
"new_urlname",
")",
"end",
"end"
] | Makes a slug of all ancestors urlnames including mine and delimit them be slash.
So the whole path is stored as urlname in the database. | [
"Makes",
"a",
"slug",
"of",
"all",
"ancestors",
"urlnames",
"including",
"mine",
"and",
"delimit",
"them",
"be",
"slash",
".",
"So",
"the",
"whole",
"path",
"is",
"stored",
"as",
"urlname",
"in",
"the",
"database",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/page/page_naming.rb#L44-L50 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/page/page_naming.rb | Alchemy.Page::PageNaming.convert_url_name | def convert_url_name(value)
url_name = convert_to_urlname(value.blank? ? name : value)
if url_name.length < 3
('-' * (3 - url_name.length)) + url_name
else
url_name
end
end | ruby | def convert_url_name(value)
url_name = convert_to_urlname(value.blank? ? name : value)
if url_name.length < 3
('-' * (3 - url_name.length)) + url_name
else
url_name
end
end | [
"def",
"convert_url_name",
"(",
"value",
")",
"url_name",
"=",
"convert_to_urlname",
"(",
"value",
".",
"blank?",
"?",
"name",
":",
"value",
")",
"if",
"url_name",
".",
"length",
"<",
"3",
"(",
"'-'",
"*",
"(",
"3",
"-",
"url_name",
".",
"length",
")",
")",
"+",
"url_name",
"else",
"url_name",
"end",
"end"
] | Converts the given name into an url friendly string.
Names shorter than 3 will be filled up with dashes,
so it does not collidate with the language code. | [
"Converts",
"the",
"given",
"name",
"into",
"an",
"url",
"friendly",
"string",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/page/page_naming.rb#L115-L122 | train |
AlchemyCMS/alchemy_cms | app/controllers/alchemy/elements_controller.rb | Alchemy.ElementsController.show | def show
@page = @element.page
@options = params[:options]
respond_to do |format|
format.html
format.js { @container_id = params[:container_id] }
end
end | ruby | def show
@page = @element.page
@options = params[:options]
respond_to do |format|
format.html
format.js { @container_id = params[:container_id] }
end
end | [
"def",
"show",
"@page",
"=",
"@element",
".",
"page",
"@options",
"=",
"params",
"[",
":options",
"]",
"respond_to",
"do",
"|",
"format",
"|",
"format",
".",
"html",
"format",
".",
"js",
"{",
"@container_id",
"=",
"params",
"[",
":container_id",
"]",
"}",
"end",
"end"
] | == Renders the element view partial
=== Accepted Formats
* html
* js (Tries to replace a given +container_id+ with the elements view partial content via jQuery.) | [
"==",
"Renders",
"the",
"element",
"view",
"partial"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/alchemy/elements_controller.rb#L19-L27 | train |
AlchemyCMS/alchemy_cms | app/helpers/alchemy/base_helper.rb | Alchemy.BaseHelper.render_icon | def render_icon(icon_class, options = {})
options = {style: 'solid'}.merge(options)
classes = [
"icon fa-fw",
"fa-#{icon_class}",
"fa#{options[:style].first}",
options[:size] ? "fa-#{options[:size]}" : nil,
options[:transform] ? "fa-#{options[:transform]}" : nil,
options[:class]
].compact
content_tag('i', nil, class: classes)
end | ruby | def render_icon(icon_class, options = {})
options = {style: 'solid'}.merge(options)
classes = [
"icon fa-fw",
"fa-#{icon_class}",
"fa#{options[:style].first}",
options[:size] ? "fa-#{options[:size]}" : nil,
options[:transform] ? "fa-#{options[:transform]}" : nil,
options[:class]
].compact
content_tag('i', nil, class: classes)
end | [
"def",
"render_icon",
"(",
"icon_class",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"style",
":",
"'solid'",
"}",
".",
"merge",
"(",
"options",
")",
"classes",
"=",
"[",
"\"icon fa-fw\"",
",",
"\"fa-#{icon_class}\"",
",",
"\"fa#{options[:style].first}\"",
",",
"options",
"[",
":size",
"]",
"?",
"\"fa-#{options[:size]}\"",
":",
"nil",
",",
"options",
"[",
":transform",
"]",
"?",
"\"fa-#{options[:transform]}\"",
":",
"nil",
",",
"options",
"[",
":class",
"]",
"]",
".",
"compact",
"content_tag",
"(",
"'i'",
",",
"nil",
",",
"class",
":",
"classes",
")",
"end"
] | Render a Fontawesome icon
@param icon_class [String] Fontawesome icon name
@param size: nil [String] Fontawesome icon size
@param transform: nil [String] Fontawesome transform style
@return [String] | [
"Render",
"a",
"Fontawesome",
"icon"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/base_helper.rb#L29-L40 | train |
AlchemyCMS/alchemy_cms | app/helpers/alchemy/base_helper.rb | Alchemy.BaseHelper.page_or_find | def page_or_find(page)
if page.is_a?(String)
page = Language.current.pages.find_by(page_layout: page)
end
if page.blank?
warning("No Page found for #{page.inspect}")
return
else
page
end
end | ruby | def page_or_find(page)
if page.is_a?(String)
page = Language.current.pages.find_by(page_layout: page)
end
if page.blank?
warning("No Page found for #{page.inspect}")
return
else
page
end
end | [
"def",
"page_or_find",
"(",
"page",
")",
"if",
"page",
".",
"is_a?",
"(",
"String",
")",
"page",
"=",
"Language",
".",
"current",
".",
"pages",
".",
"find_by",
"(",
"page_layout",
":",
"page",
")",
"end",
"if",
"page",
".",
"blank?",
"warning",
"(",
"\"No Page found for #{page.inspect}\"",
")",
"return",
"else",
"page",
"end",
"end"
] | Checks if the given argument is a String or a Page object.
If a String is given, it tries to find the page via page_layout
Logs a warning if no page is given. | [
"Checks",
"if",
"the",
"given",
"argument",
"is",
"a",
"String",
"or",
"a",
"Page",
"object",
".",
"If",
"a",
"String",
"is",
"given",
"it",
"tries",
"to",
"find",
"the",
"page",
"via",
"page_layout",
"Logs",
"a",
"warning",
"if",
"no",
"page",
"is",
"given",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/base_helper.rb#L73-L83 | train |
AlchemyCMS/alchemy_cms | app/controllers/alchemy/pages_controller.rb | Alchemy.PagesController.load_page | def load_page
@page ||= Language.current.pages.contentpages.find_by(
urlname: params[:urlname],
language_code: params[:locale] || Language.current.code
)
end | ruby | def load_page
@page ||= Language.current.pages.contentpages.find_by(
urlname: params[:urlname],
language_code: params[:locale] || Language.current.code
)
end | [
"def",
"load_page",
"@page",
"||=",
"Language",
".",
"current",
".",
"pages",
".",
"contentpages",
".",
"find_by",
"(",
"urlname",
":",
"params",
"[",
":urlname",
"]",
",",
"language_code",
":",
"params",
"[",
":locale",
"]",
"||",
"Language",
".",
"current",
".",
"code",
")",
"end"
] | == Loads page by urlname
If a locale is specified in the request parameters,
scope pages to it to make sure we can raise a 404 if the urlname
is not available in that language.
@return Alchemy::Page
@return NilClass | [
"==",
"Loads",
"page",
"by",
"urlname"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/alchemy/pages_controller.rb#L110-L115 | train |
AlchemyCMS/alchemy_cms | app/controllers/alchemy/pages_controller.rb | Alchemy.PagesController.render_fresh_page? | def render_fresh_page?
must_not_cache? || stale?(etag: page_etag,
last_modified: @page.published_at,
public: [email protected],
template: 'pages/show')
end | ruby | def render_fresh_page?
must_not_cache? || stale?(etag: page_etag,
last_modified: @page.published_at,
public: [email protected],
template: 'pages/show')
end | [
"def",
"render_fresh_page?",
"must_not_cache?",
"||",
"stale?",
"(",
"etag",
":",
"page_etag",
",",
"last_modified",
":",
"@page",
".",
"published_at",
",",
"public",
":",
"!",
"@page",
".",
"restricted",
",",
"template",
":",
"'pages/show'",
")",
"end"
] | We only render the page if either the cache is disabled for this page
or the cache is stale, because it's been republished by the user. | [
"We",
"only",
"render",
"the",
"page",
"if",
"either",
"the",
"cache",
"is",
"disabled",
"for",
"this",
"page",
"or",
"the",
"cache",
"is",
"stale",
"because",
"it",
"s",
"been",
"republished",
"by",
"the",
"user",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/alchemy/pages_controller.rb#L192-L197 | train |
AlchemyCMS/alchemy_cms | app/helpers/alchemy/essences_helper.rb | Alchemy.EssencesHelper.render_essence_view_by_name | def render_essence_view_by_name(element, name, options = {}, html_options = {})
if element.blank?
warning('Element is nil')
return ""
end
content = element.content_by_name(name)
render_essence_view(content, options, html_options)
end | ruby | def render_essence_view_by_name(element, name, options = {}, html_options = {})
if element.blank?
warning('Element is nil')
return ""
end
content = element.content_by_name(name)
render_essence_view(content, options, html_options)
end | [
"def",
"render_essence_view_by_name",
"(",
"element",
",",
"name",
",",
"options",
"=",
"{",
"}",
",",
"html_options",
"=",
"{",
"}",
")",
"if",
"element",
".",
"blank?",
"warning",
"(",
"'Element is nil'",
")",
"return",
"\"\"",
"end",
"content",
"=",
"element",
".",
"content_by_name",
"(",
"name",
")",
"render_essence_view",
"(",
"content",
",",
"options",
",",
"html_options",
")",
"end"
] | Renders the +Essence+ view partial from +Element+ by name.
Pass the name of the +Content+ from +Element+ as second argument.
== Example:
This renders the +Content+ named "intro" from element.
<%= render_essence_view_by_name(element, "intro") %> | [
"Renders",
"the",
"+",
"Essence",
"+",
"view",
"partial",
"from",
"+",
"Element",
"+",
"by",
"name",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/essences_helper.rb#L41-L48 | train |
AlchemyCMS/alchemy_cms | app/helpers/alchemy/essences_helper.rb | Alchemy.EssencesHelper.render_essence | def render_essence(content, part = :view, options = {}, html_options = {})
options = {for_view: {}, for_editor: {}}.update(options)
if content.nil?
return part == :view ? "" : warning('Content is nil', Alchemy.t(:content_not_found))
elsif content.essence.nil?
return part == :view ? "" : warning('Essence is nil', Alchemy.t(:content_essence_not_found))
end
render partial: "alchemy/essences/#{content.essence_partial_name}_#{part}", locals: {
content: content,
options: options["for_#{part}".to_sym],
html_options: html_options
}
end | ruby | def render_essence(content, part = :view, options = {}, html_options = {})
options = {for_view: {}, for_editor: {}}.update(options)
if content.nil?
return part == :view ? "" : warning('Content is nil', Alchemy.t(:content_not_found))
elsif content.essence.nil?
return part == :view ? "" : warning('Essence is nil', Alchemy.t(:content_essence_not_found))
end
render partial: "alchemy/essences/#{content.essence_partial_name}_#{part}", locals: {
content: content,
options: options["for_#{part}".to_sym],
html_options: html_options
}
end | [
"def",
"render_essence",
"(",
"content",
",",
"part",
"=",
":view",
",",
"options",
"=",
"{",
"}",
",",
"html_options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"for_view",
":",
"{",
"}",
",",
"for_editor",
":",
"{",
"}",
"}",
".",
"update",
"(",
"options",
")",
"if",
"content",
".",
"nil?",
"return",
"part",
"==",
":view",
"?",
"\"\"",
":",
"warning",
"(",
"'Content is nil'",
",",
"Alchemy",
".",
"t",
"(",
":content_not_found",
")",
")",
"elsif",
"content",
".",
"essence",
".",
"nil?",
"return",
"part",
"==",
":view",
"?",
"\"\"",
":",
"warning",
"(",
"'Essence is nil'",
",",
"Alchemy",
".",
"t",
"(",
":content_essence_not_found",
")",
")",
"end",
"render",
"partial",
":",
"\"alchemy/essences/#{content.essence_partial_name}_#{part}\"",
",",
"locals",
":",
"{",
"content",
":",
"content",
",",
"options",
":",
"options",
"[",
"\"for_#{part}\"",
".",
"to_sym",
"]",
",",
"html_options",
":",
"html_options",
"}",
"end"
] | Renders the +Esssence+ partial for given +Content+.
The helper renders the view partial as default.
Pass +:editor+ as second argument to render the editor partial
== Options:
You can pass a options Hash to each type of essence partial as third argument.
This Hash is available as +options+ local variable.
for_view: {}
for_editor: {} | [
"Renders",
"the",
"+",
"Esssence",
"+",
"partial",
"for",
"given",
"+",
"Content",
"+",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/essences_helper.rb#L65-L77 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/controller_actions.rb | Alchemy.ControllerActions.current_alchemy_user | def current_alchemy_user
current_user_method = Alchemy.current_user_method
raise NoCurrentUserFoundError if !respond_to?(current_user_method, true)
send current_user_method
end | ruby | def current_alchemy_user
current_user_method = Alchemy.current_user_method
raise NoCurrentUserFoundError if !respond_to?(current_user_method, true)
send current_user_method
end | [
"def",
"current_alchemy_user",
"current_user_method",
"=",
"Alchemy",
".",
"current_user_method",
"raise",
"NoCurrentUserFoundError",
"if",
"!",
"respond_to?",
"(",
"current_user_method",
",",
"true",
")",
"send",
"current_user_method",
"end"
] | The current authorized user.
In order to have Alchemy's authorization work, you have to
provide a +current_user+ method in your app's ApplicationController,
that returns the current user. To change the method +current_alchemy_user+
will call, set +Alchemy.current_user_method+ to a different method name.
If you don't have an App that can provide a +current_user+ object,
you can install the `alchemy-devise` gem that provides everything you need. | [
"The",
"current",
"authorized",
"user",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/controller_actions.rb#L36-L40 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/controller_actions.rb | Alchemy.ControllerActions.set_alchemy_language | def set_alchemy_language(lang = nil)
if lang
@language = lang.is_a?(Language) ? lang : load_alchemy_language_from_id_or_code(lang)
else
# find the best language and remember it for later
@language = load_alchemy_language_from_params ||
load_alchemy_language_from_session ||
Language.default
end
store_current_alchemy_language(@language)
end | ruby | def set_alchemy_language(lang = nil)
if lang
@language = lang.is_a?(Language) ? lang : load_alchemy_language_from_id_or_code(lang)
else
# find the best language and remember it for later
@language = load_alchemy_language_from_params ||
load_alchemy_language_from_session ||
Language.default
end
store_current_alchemy_language(@language)
end | [
"def",
"set_alchemy_language",
"(",
"lang",
"=",
"nil",
")",
"if",
"lang",
"@language",
"=",
"lang",
".",
"is_a?",
"(",
"Language",
")",
"?",
"lang",
":",
"load_alchemy_language_from_id_or_code",
"(",
"lang",
")",
"else",
"# find the best language and remember it for later",
"@language",
"=",
"load_alchemy_language_from_params",
"||",
"load_alchemy_language_from_session",
"||",
"Language",
".",
"default",
"end",
"store_current_alchemy_language",
"(",
"@language",
")",
"end"
] | Try to find and stores current language for Alchemy. | [
"Try",
"to",
"find",
"and",
"stores",
"current",
"language",
"for",
"Alchemy",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/controller_actions.rb#L63-L73 | train |
AlchemyCMS/alchemy_cms | lib/alchemy/controller_actions.rb | Alchemy.ControllerActions.store_current_alchemy_language | def store_current_alchemy_language(language)
if language && language.id
session[:alchemy_language_id] = language.id
Language.current = language
end
end | ruby | def store_current_alchemy_language(language)
if language && language.id
session[:alchemy_language_id] = language.id
Language.current = language
end
end | [
"def",
"store_current_alchemy_language",
"(",
"language",
")",
"if",
"language",
"&&",
"language",
".",
"id",
"session",
"[",
":alchemy_language_id",
"]",
"=",
"language",
".",
"id",
"Language",
".",
"current",
"=",
"language",
"end",
"end"
] | Stores language's id in the session.
Also stores language in +Language.current+ | [
"Stores",
"language",
"s",
"id",
"in",
"the",
"session",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/controller_actions.rb#L98-L103 | train |
AlchemyCMS/alchemy_cms | app/helpers/alchemy/elements_helper.rb | Alchemy.ElementsHelper.render_elements | def render_elements(options = {})
options = {
from_page: @page,
render_format: 'html'
}.update(options)
if options[:sort_by]
Alchemy::Deprecation.warn "options[:sort_by] has been removed without replacement. " \
"Please implement your own element sorting by passing a custom finder instance to options[:finder]."
end
if options[:from_cell]
Alchemy::Deprecation.warn "options[:from_cell] has been removed without replacement. " \
"Please `render element.nested_elements.available` instead."
end
finder = options[:finder] || Alchemy::ElementsFinder.new(options)
elements = finder.elements(page: options[:from_page])
buff = []
elements.each_with_index do |element, i|
buff << render_element(element, options, i + 1)
end
buff.join(options[:separator]).html_safe
end | ruby | def render_elements(options = {})
options = {
from_page: @page,
render_format: 'html'
}.update(options)
if options[:sort_by]
Alchemy::Deprecation.warn "options[:sort_by] has been removed without replacement. " \
"Please implement your own element sorting by passing a custom finder instance to options[:finder]."
end
if options[:from_cell]
Alchemy::Deprecation.warn "options[:from_cell] has been removed without replacement. " \
"Please `render element.nested_elements.available` instead."
end
finder = options[:finder] || Alchemy::ElementsFinder.new(options)
elements = finder.elements(page: options[:from_page])
buff = []
elements.each_with_index do |element, i|
buff << render_element(element, options, i + 1)
end
buff.join(options[:separator]).html_safe
end | [
"def",
"render_elements",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"from_page",
":",
"@page",
",",
"render_format",
":",
"'html'",
"}",
".",
"update",
"(",
"options",
")",
"if",
"options",
"[",
":sort_by",
"]",
"Alchemy",
"::",
"Deprecation",
".",
"warn",
"\"options[:sort_by] has been removed without replacement. \"",
"\"Please implement your own element sorting by passing a custom finder instance to options[:finder].\"",
"end",
"if",
"options",
"[",
":from_cell",
"]",
"Alchemy",
"::",
"Deprecation",
".",
"warn",
"\"options[:from_cell] has been removed without replacement. \"",
"\"Please `render element.nested_elements.available` instead.\"",
"end",
"finder",
"=",
"options",
"[",
":finder",
"]",
"||",
"Alchemy",
"::",
"ElementsFinder",
".",
"new",
"(",
"options",
")",
"elements",
"=",
"finder",
".",
"elements",
"(",
"page",
":",
"options",
"[",
":from_page",
"]",
")",
"buff",
"=",
"[",
"]",
"elements",
".",
"each_with_index",
"do",
"|",
"element",
",",
"i",
"|",
"buff",
"<<",
"render_element",
"(",
"element",
",",
"options",
",",
"i",
"+",
"1",
")",
"end",
"buff",
".",
"join",
"(",
"options",
"[",
":separator",
"]",
")",
".",
"html_safe",
"end"
] | Renders elements from given page
== Examples:
=== Render only certain elements:
<header>
<%= render_elements only: ['header', 'claim'] %>
</header>
<section id="content">
<%= render_elements except: ['header', 'claim'] %>
</section>
=== Render elements from global page:
<footer>
<%= render_elements from_page: 'footer' %>
</footer>
=== Fallback to elements from global page:
You can use the fallback option as an override for elements that are stored on another page.
So you can take elements from a global page and only if the user adds an element on current page the
local one gets rendered.
1. You have to pass the the name of the element the fallback is for as <tt>for</tt> key.
2. You have to pass a <tt>page_layout</tt> name or {Alchemy::Page} from where the fallback elements is taken from as <tt>from</tt> key.
3. You can pass the name of element to fallback with as <tt>with</tt> key. This is optional (the element name from the <tt>for</tt> key is taken as default).
<%= render_elements(fallback: {
for: 'contact_teaser',
from: 'sidebar',
with: 'contact_teaser'
}) %>
=== Custom elements finder:
Having a custom element finder class:
class MyCustomNewsArchive
def elements(page:)
news_page.elements.available.named('news').order(created_at: :desc)
end
private
def news_page
Alchemy::Page.where(page_layout: 'news-archive')
end
end
In your view:
<div class="news-archive">
<%= render_elements finder: MyCustomNewsArchive.new %>
</div>
@option options [Alchemy::Page|String] :from_page (@page)
The page the elements are rendered from. You can pass a page_layout String or a {Alchemy::Page} object.
@option options [Array<String>|String] :only
A list of element names only to be rendered.
@option options [Array<String>|String] :except
A list of element names not to be rendered.
@option options [Number] :count
The amount of elements to be rendered (begins with first element found)
@option options [Number] :offset
The offset to begin loading elements from
@option options [Hash] :fallback
Define elements that are rendered from another page.
@option options [Boolean] :random (false)
Randomize the output of elements
@option options [Boolean] :reverse (false)
Reverse the rendering order
@option options [String] :separator
A string that will be used to join the element partials.
@option options [Class] :finder (Alchemy::ElementsFinder)
A class instance that will return elements that get rendered.
Use this for your custom element loading logic in views. | [
"Renders",
"elements",
"from",
"given",
"page"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/elements_helper.rb#L92-L116 | train |
AlchemyCMS/alchemy_cms | app/helpers/alchemy/elements_helper.rb | Alchemy.ElementsHelper.element_preview_code | def element_preview_code(element)
if respond_to?(:tag_options)
tag_options(element_preview_code_attributes(element))
else
# Rails 5.1 uses TagBuilder
tag_builder.tag_options(element_preview_code_attributes(element))
end
end | ruby | def element_preview_code(element)
if respond_to?(:tag_options)
tag_options(element_preview_code_attributes(element))
else
# Rails 5.1 uses TagBuilder
tag_builder.tag_options(element_preview_code_attributes(element))
end
end | [
"def",
"element_preview_code",
"(",
"element",
")",
"if",
"respond_to?",
"(",
":tag_options",
")",
"tag_options",
"(",
"element_preview_code_attributes",
"(",
"element",
")",
")",
"else",
"# Rails 5.1 uses TagBuilder",
"tag_builder",
".",
"tag_options",
"(",
"element_preview_code_attributes",
"(",
"element",
")",
")",
"end",
"end"
] | Renders the HTML tag attributes required for preview mode. | [
"Renders",
"the",
"HTML",
"tag",
"attributes",
"required",
"for",
"preview",
"mode",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/elements_helper.rb#L202-L209 | train |
AlchemyCMS/alchemy_cms | app/helpers/alchemy/elements_helper.rb | Alchemy.ElementsHelper.element_tags_attributes | def element_tags_attributes(element, options = {})
options = {
formatter: lambda { |tags| tags.join(' ') }
}.merge(options)
return {} if !element.taggable? || element.tag_list.blank?
{ 'data-element-tags' => options[:formatter].call(element.tag_list) }
end | ruby | def element_tags_attributes(element, options = {})
options = {
formatter: lambda { |tags| tags.join(' ') }
}.merge(options)
return {} if !element.taggable? || element.tag_list.blank?
{ 'data-element-tags' => options[:formatter].call(element.tag_list) }
end | [
"def",
"element_tags_attributes",
"(",
"element",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"formatter",
":",
"lambda",
"{",
"|",
"tags",
"|",
"tags",
".",
"join",
"(",
"' '",
")",
"}",
"}",
".",
"merge",
"(",
"options",
")",
"return",
"{",
"}",
"if",
"!",
"element",
".",
"taggable?",
"||",
"element",
".",
"tag_list",
".",
"blank?",
"{",
"'data-element-tags'",
"=>",
"options",
"[",
":formatter",
"]",
".",
"call",
"(",
"element",
".",
"tag_list",
")",
"}",
"end"
] | Returns the element's tags information as an attribute hash.
@param [Alchemy::Element] element The {Alchemy::Element} you want to render the tags from.
@option options [Proc] :formatter
('lambda { |tags| tags.join(' ') }')
Lambda converting array of tags to a string.
@return [Hash]
HTML tag attributes containing the element's tag information. | [
"Returns",
"the",
"element",
"s",
"tags",
"information",
"as",
"an",
"attribute",
"hash",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/elements_helper.rb#L245-L252 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/element.rb | Alchemy.Element.next | def next(name = nil)
elements = page.elements.published.where('position > ?', position)
select_element(elements, name, :asc)
end | ruby | def next(name = nil)
elements = page.elements.published.where('position > ?', position)
select_element(elements, name, :asc)
end | [
"def",
"next",
"(",
"name",
"=",
"nil",
")",
"elements",
"=",
"page",
".",
"elements",
".",
"published",
".",
"where",
"(",
"'position > ?'",
",",
"position",
")",
"select_element",
"(",
"elements",
",",
"name",
",",
":asc",
")",
"end"
] | Returns next public element from same page.
Pass an element name to get next of this kind. | [
"Returns",
"next",
"public",
"element",
"from",
"same",
"page",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/element.rb#L195-L198 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/element.rb | Alchemy.Element.copy_nested_elements_to | def copy_nested_elements_to(target_element)
nested_elements.map do |nested_element|
Element.copy(nested_element, {
parent_element_id: target_element.id,
page_id: target_element.page_id
})
end
end | ruby | def copy_nested_elements_to(target_element)
nested_elements.map do |nested_element|
Element.copy(nested_element, {
parent_element_id: target_element.id,
page_id: target_element.page_id
})
end
end | [
"def",
"copy_nested_elements_to",
"(",
"target_element",
")",
"nested_elements",
".",
"map",
"do",
"|",
"nested_element",
"|",
"Element",
".",
"copy",
"(",
"nested_element",
",",
"{",
"parent_element_id",
":",
"target_element",
".",
"id",
",",
"page_id",
":",
"target_element",
".",
"page_id",
"}",
")",
"end",
"end"
] | Copy all nested elements from current element to given target element. | [
"Copy",
"all",
"nested",
"elements",
"from",
"current",
"element",
"to",
"given",
"target",
"element",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/element.rb#L282-L289 | train |
AlchemyCMS/alchemy_cms | app/models/alchemy/element/element_essences.rb | Alchemy.Element::ElementEssences.essence_error_messages | def essence_error_messages
messages = []
essence_errors.each do |content_name, errors|
errors.each do |error|
messages << Alchemy.t(
"#{name}.#{content_name}.#{error}",
scope: 'content_validations',
default: [
"fields.#{content_name}.#{error}".to_sym,
"errors.#{error}".to_sym
],
field: Content.translated_label_for(content_name, name)
)
end
end
messages
end | ruby | def essence_error_messages
messages = []
essence_errors.each do |content_name, errors|
errors.each do |error|
messages << Alchemy.t(
"#{name}.#{content_name}.#{error}",
scope: 'content_validations',
default: [
"fields.#{content_name}.#{error}".to_sym,
"errors.#{error}".to_sym
],
field: Content.translated_label_for(content_name, name)
)
end
end
messages
end | [
"def",
"essence_error_messages",
"messages",
"=",
"[",
"]",
"essence_errors",
".",
"each",
"do",
"|",
"content_name",
",",
"errors",
"|",
"errors",
".",
"each",
"do",
"|",
"error",
"|",
"messages",
"<<",
"Alchemy",
".",
"t",
"(",
"\"#{name}.#{content_name}.#{error}\"",
",",
"scope",
":",
"'content_validations'",
",",
"default",
":",
"[",
"\"fields.#{content_name}.#{error}\"",
".",
"to_sym",
",",
"\"errors.#{error}\"",
".",
"to_sym",
"]",
",",
"field",
":",
"Content",
".",
"translated_label_for",
"(",
"content_name",
",",
"name",
")",
")",
"end",
"end",
"messages",
"end"
] | Essence validation errors
== Error messages are translated via I18n
Inside your translation file add translations like:
alchemy:
content_validations:
name_of_the_element:
name_of_the_content:
validation_error_type: Error Message
NOTE: +validation_error_type+ has to be one of:
* blank
* taken
* invalid
=== Example:
de:
alchemy:
content_validations:
contactform:
email:
invalid: 'Die Email hat nicht das richtige Format'
== Error message translation fallbacks
In order to not translate every single content for every element
you can provide default error messages per content name:
=== Example
en:
alchemy:
content_validations:
fields:
email:
invalid: E-Mail has wrong format
blank: E-Mail can't be blank
And even further you can provide general field agnostic error messages:
=== Example
en:
alchemy:
content_validations:
errors:
invalid: %{field} has wrong format
blank: %{field} can't be blank | [
"Essence",
"validation",
"errors"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/element/element_essences.rb#L93-L109 | train |
AlchemyCMS/alchemy_cms | app/helpers/alchemy/pages_helper.rb | Alchemy.PagesHelper.language_links | def language_links(options = {})
options = {
linkname: 'name',
show_title: true,
spacer: '',
reverse: false
}.merge(options)
languages = Language.on_current_site.published.with_root_page.order("name #{options[:reverse] ? 'DESC' : 'ASC'}")
return nil if languages.count < 2
render(
partial: "alchemy/language_links/language",
collection: languages,
spacer_template: "alchemy/language_links/spacer",
locals: {languages: languages, options: options}
)
end | ruby | def language_links(options = {})
options = {
linkname: 'name',
show_title: true,
spacer: '',
reverse: false
}.merge(options)
languages = Language.on_current_site.published.with_root_page.order("name #{options[:reverse] ? 'DESC' : 'ASC'}")
return nil if languages.count < 2
render(
partial: "alchemy/language_links/language",
collection: languages,
spacer_template: "alchemy/language_links/spacer",
locals: {languages: languages, options: options}
)
end | [
"def",
"language_links",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"linkname",
":",
"'name'",
",",
"show_title",
":",
"true",
",",
"spacer",
":",
"''",
",",
"reverse",
":",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"languages",
"=",
"Language",
".",
"on_current_site",
".",
"published",
".",
"with_root_page",
".",
"order",
"(",
"\"name #{options[:reverse] ? 'DESC' : 'ASC'}\"",
")",
"return",
"nil",
"if",
"languages",
".",
"count",
"<",
"2",
"render",
"(",
"partial",
":",
"\"alchemy/language_links/language\"",
",",
"collection",
":",
"languages",
",",
"spacer_template",
":",
"\"alchemy/language_links/spacer\"",
",",
"locals",
":",
"{",
"languages",
":",
"languages",
",",
"options",
":",
"options",
"}",
")",
"end"
] | Renders links to language root pages of all published languages.
@option options linkname [String] ('name')
Renders name/code of language, or I18n translation for code.
@option options show_title [Boolean] (true)
Renders title attributes for the links.
@option options spacer [String] ('')
Renders the passed spacer string. You can also overwrite the spacer partial: "alchemy/language_links/_spacer".
@option options reverse [Boolean] (false)
Reverses the ordering of the links. | [
"Renders",
"links",
"to",
"language",
"root",
"pages",
"of",
"all",
"published",
"languages",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/pages_helper.rb#L26-L41 | train |
AlchemyCMS/alchemy_cms | app/helpers/alchemy/pages_helper.rb | Alchemy.PagesHelper.render_navigation | def render_navigation(options = {}, html_options = {})
options = {
submenu: false,
all_sub_menues: false,
from_page: @root_page || Language.current_root_page,
spacer: nil,
navigation_partial: 'alchemy/navigation/renderer',
navigation_link_partial: 'alchemy/navigation/link',
show_nonactive: false,
restricted_only: false,
show_title: true,
reverse: false,
reverse_children: false
}.merge(options)
page = page_or_find(options[:from_page])
return nil if page.blank?
pages = page.children.accessible_by(current_ability, :see)
pages = pages.restricted if options.delete(:restricted_only)
if depth = options[:deepness]
pages = pages.where('depth <= ?', depth)
end
if options[:reverse]
pages.reverse!
end
render options[:navigation_partial],
options: options,
pages: pages,
html_options: html_options
end | ruby | def render_navigation(options = {}, html_options = {})
options = {
submenu: false,
all_sub_menues: false,
from_page: @root_page || Language.current_root_page,
spacer: nil,
navigation_partial: 'alchemy/navigation/renderer',
navigation_link_partial: 'alchemy/navigation/link',
show_nonactive: false,
restricted_only: false,
show_title: true,
reverse: false,
reverse_children: false
}.merge(options)
page = page_or_find(options[:from_page])
return nil if page.blank?
pages = page.children.accessible_by(current_ability, :see)
pages = pages.restricted if options.delete(:restricted_only)
if depth = options[:deepness]
pages = pages.where('depth <= ?', depth)
end
if options[:reverse]
pages.reverse!
end
render options[:navigation_partial],
options: options,
pages: pages,
html_options: html_options
end | [
"def",
"render_navigation",
"(",
"options",
"=",
"{",
"}",
",",
"html_options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"submenu",
":",
"false",
",",
"all_sub_menues",
":",
"false",
",",
"from_page",
":",
"@root_page",
"||",
"Language",
".",
"current_root_page",
",",
"spacer",
":",
"nil",
",",
"navigation_partial",
":",
"'alchemy/navigation/renderer'",
",",
"navigation_link_partial",
":",
"'alchemy/navigation/link'",
",",
"show_nonactive",
":",
"false",
",",
"restricted_only",
":",
"false",
",",
"show_title",
":",
"true",
",",
"reverse",
":",
"false",
",",
"reverse_children",
":",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"page",
"=",
"page_or_find",
"(",
"options",
"[",
":from_page",
"]",
")",
"return",
"nil",
"if",
"page",
".",
"blank?",
"pages",
"=",
"page",
".",
"children",
".",
"accessible_by",
"(",
"current_ability",
",",
":see",
")",
"pages",
"=",
"pages",
".",
"restricted",
"if",
"options",
".",
"delete",
"(",
":restricted_only",
")",
"if",
"depth",
"=",
"options",
"[",
":deepness",
"]",
"pages",
"=",
"pages",
".",
"where",
"(",
"'depth <= ?'",
",",
"depth",
")",
"end",
"if",
"options",
"[",
":reverse",
"]",
"pages",
".",
"reverse!",
"end",
"render",
"options",
"[",
":navigation_partial",
"]",
",",
"options",
":",
"options",
",",
"pages",
":",
"pages",
",",
"html_options",
":",
"html_options",
"end"
] | Renders the navigation.
It produces a html <ul><li></li></ul> structure with all necessary classes so you can produce every navigation the web uses today.
I.E. dropdown-navigations, simple mainnavigations or even complex nested ones.
=== HTML output:
<ul class="navigation level_1">
<li class="first home"><a href="/home" class="active" title="Homepage" lang="en" data-page-id="1">Homepage</a></li>
<li class="contact"><a href="/contact" title="Contact" lang="en" data-page-id="2">Contact</a></li>
<li class="last imprint"><a href="/imprint" title="Imprint" lang="en" data-page-id="3">Imprint</a></li>
</ul>
As you can see: Everything you need.
Not pleased with the way Alchemy produces the navigation structure?
Then feel free to overwrite the partials (_renderer.html.erb and _link.html.erb) found in +views/navigation/+ or pass different partials via the options +:navigation_partial+ and +:navigation_link_partial+.
=== Passing HTML classes and ids to the renderer
A second hash can be passed as html_options to the navigation renderer partial.
==== Example:
<%= render_navigation({from_page: 'subnavi'}, {class: 'navigation', id: 'subnavigation'}) %>
@option options submenu [Boolean] (false)
Do you want a nested <ul> <li> structure for the deeper levels of your navigation, or not?
Used to display the subnavigation within the mainnaviagtion. I.e. for dropdown menues.
@option options all_sub_menues [Boolean] (false)
Renders the whole page tree.
@option options from_page [Alchemy::Page] (@root_page)
Do you want to render a navigation from a different page then the current page?
Then pass an Page instance or a Alchemy::PageLayout name as string.
@option options spacer [String] (nil)
A spacer for the entries can be passed.
Simple string, or even a complex html structure.
I.e: "<span class='spacer'>|</spacer>".
@option options navigation_partial [String] ("navigation/renderer")
Pass a different partial to be taken for the navigation rendering.
Alternatively you could override the +app/views/alchemy/navigation/renderer+ partial in your app.
@option options navigation_link_partial [String] ("navigation/link")
Alchemy places an <a> html link in <li> tags.
The tag automatically has an active css class if necessary.
So styling is everything. But maybe you don't want this.
So feel free to make you own partial and pass the filename here.
Alternatively you could override the +app/views/alchemy/navigation/link+ partial in your app.
@option options show_nonactive [Boolean] (false)
Commonly Alchemy only displays the submenu of the active page (if submenu: true).
If you want to display all child pages then pass true (together with submenu: true of course).
I.e. for css-driven drop down menues.
@option options show_title [Boolean] (true)
For our beloved SEOs :)
Appends a title attribute to all links and places the +page.title+ content into it.
@option options restricted_only [Boolean] (false)
Render only restricted pages. I.E for members only navigations.
@option options reverse [Boolean] (false)
Reverse the output of the pages
@option options reverse_children [Boolean] (false)
Like reverse option, but only reverse the children of the first level
@option options deepness [Fixnum] (nil)
Show only pages up to this depth. | [
"Renders",
"the",
"navigation",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/pages_helper.rb#L151-L179 | train |
AlchemyCMS/alchemy_cms | app/helpers/alchemy/pages_helper.rb | Alchemy.PagesHelper.external_page_css_class | def external_page_css_class(page)
return nil if !page.redirects_to_external?
request.path.split('/').delete_if(&:blank?).first == page.urlname.gsub(/^\//, '') ? 'active' : nil
end | ruby | def external_page_css_class(page)
return nil if !page.redirects_to_external?
request.path.split('/').delete_if(&:blank?).first == page.urlname.gsub(/^\//, '') ? 'active' : nil
end | [
"def",
"external_page_css_class",
"(",
"page",
")",
"return",
"nil",
"if",
"!",
"page",
".",
"redirects_to_external?",
"request",
".",
"path",
".",
"split",
"(",
"'/'",
")",
".",
"delete_if",
"(",
":blank?",
")",
".",
"first",
"==",
"page",
".",
"urlname",
".",
"gsub",
"(",
"/",
"\\/",
"/",
",",
"''",
")",
"?",
"'active'",
":",
"nil",
"end"
] | Returns +'active'+ if the given external page is in the current url path or +nil+. | [
"Returns",
"+",
"active",
"+",
"if",
"the",
"given",
"external",
"page",
"is",
"in",
"the",
"current",
"url",
"path",
"or",
"+",
"nil",
"+",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/pages_helper.rb#L217-L220 | train |
AlchemyCMS/alchemy_cms | app/helpers/alchemy/pages_helper.rb | Alchemy.PagesHelper.render_breadcrumb | def render_breadcrumb(options = {})
options = {
separator: ">",
page: @page,
restricted_only: false,
reverse: false,
link_active_page: false
}.merge(options)
pages = Page.
ancestors_for(options[:page]).
accessible_by(current_ability, :see)
if options.delete(:restricted_only)
pages = pages.restricted
end
if options.delete(:reverse)
pages = pages.reorder('lft DESC')
end
if options[:without].present?
without = options.delete(:without)
pages = pages.where.not(id: without.try(:collect, &:id) || without.id)
end
render 'alchemy/breadcrumb/wrapper', pages: pages, options: options
end | ruby | def render_breadcrumb(options = {})
options = {
separator: ">",
page: @page,
restricted_only: false,
reverse: false,
link_active_page: false
}.merge(options)
pages = Page.
ancestors_for(options[:page]).
accessible_by(current_ability, :see)
if options.delete(:restricted_only)
pages = pages.restricted
end
if options.delete(:reverse)
pages = pages.reorder('lft DESC')
end
if options[:without].present?
without = options.delete(:without)
pages = pages.where.not(id: without.try(:collect, &:id) || without.id)
end
render 'alchemy/breadcrumb/wrapper', pages: pages, options: options
end | [
"def",
"render_breadcrumb",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"separator",
":",
"\">\"",
",",
"page",
":",
"@page",
",",
"restricted_only",
":",
"false",
",",
"reverse",
":",
"false",
",",
"link_active_page",
":",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"pages",
"=",
"Page",
".",
"ancestors_for",
"(",
"options",
"[",
":page",
"]",
")",
".",
"accessible_by",
"(",
"current_ability",
",",
":see",
")",
"if",
"options",
".",
"delete",
"(",
":restricted_only",
")",
"pages",
"=",
"pages",
".",
"restricted",
"end",
"if",
"options",
".",
"delete",
"(",
":reverse",
")",
"pages",
"=",
"pages",
".",
"reorder",
"(",
"'lft DESC'",
")",
"end",
"if",
"options",
"[",
":without",
"]",
".",
"present?",
"without",
"=",
"options",
".",
"delete",
"(",
":without",
")",
"pages",
"=",
"pages",
".",
"where",
".",
"not",
"(",
"id",
":",
"without",
".",
"try",
"(",
":collect",
",",
":id",
")",
"||",
"without",
".",
"id",
")",
"end",
"render",
"'alchemy/breadcrumb/wrapper'",
",",
"pages",
":",
"pages",
",",
"options",
":",
"options",
"end"
] | Returns page links in a breadcrumb beginning from root to current page.
=== Options:
separator: %(<span class="separator">></span>) # Maybe you don't want this separator. Pass another one.
page: @page # Pass a different Page instead of the default (@page).
without: nil # Pass Page object or array of Pages that must not be displayed.
restricted_only: false # Pass boolean for displaying restricted pages only.
reverse: false # Pass boolean for displaying breadcrumb in reversed reversed. | [
"Returns",
"page",
"links",
"in",
"a",
"breadcrumb",
"beginning",
"from",
"root",
"to",
"current",
"page",
"."
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/pages_helper.rb#L232-L259 | train |
AlchemyCMS/alchemy_cms | app/helpers/alchemy/pages_helper.rb | Alchemy.PagesHelper.page_title | def page_title(options = {})
return "" if @page.title.blank?
options = {
prefix: "",
suffix: "",
separator: ""
}.update(options)
title_parts = [options[:prefix]]
if response.status == 200
title_parts << @page.title
else
title_parts << response.status
end
title_parts << options[:suffix]
title_parts.reject(&:blank?).join(options[:separator]).html_safe
end | ruby | def page_title(options = {})
return "" if @page.title.blank?
options = {
prefix: "",
suffix: "",
separator: ""
}.update(options)
title_parts = [options[:prefix]]
if response.status == 200
title_parts << @page.title
else
title_parts << response.status
end
title_parts << options[:suffix]
title_parts.reject(&:blank?).join(options[:separator]).html_safe
end | [
"def",
"page_title",
"(",
"options",
"=",
"{",
"}",
")",
"return",
"\"\"",
"if",
"@page",
".",
"title",
".",
"blank?",
"options",
"=",
"{",
"prefix",
":",
"\"\"",
",",
"suffix",
":",
"\"\"",
",",
"separator",
":",
"\"\"",
"}",
".",
"update",
"(",
"options",
")",
"title_parts",
"=",
"[",
"options",
"[",
":prefix",
"]",
"]",
"if",
"response",
".",
"status",
"==",
"200",
"title_parts",
"<<",
"@page",
".",
"title",
"else",
"title_parts",
"<<",
"response",
".",
"status",
"end",
"title_parts",
"<<",
"options",
"[",
":suffix",
"]",
"title_parts",
".",
"reject",
"(",
":blank?",
")",
".",
"join",
"(",
"options",
"[",
":separator",
"]",
")",
".",
"html_safe",
"end"
] | Returns current page title
=== Options:
prefix: "" # Prefix
separator: "" # Separating prefix and title | [
"Returns",
"current",
"page",
"title"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/pages_helper.rb#L268-L283 | train |
AlchemyCMS/alchemy_cms | app/controllers/alchemy/api/pages_controller.rb | Alchemy.Api::PagesController.index | def index
# Fix for cancancan not able to merge multiple AR scopes for logged in users
if can? :edit_content, Alchemy::Page
@pages = Page.all
else
@pages = Page.accessible_by(current_ability, :index)
end
if params[:page_layout].present?
@pages = @pages.where(page_layout: params[:page_layout])
end
render json: @pages, adapter: :json, root: :pages
end | ruby | def index
# Fix for cancancan not able to merge multiple AR scopes for logged in users
if can? :edit_content, Alchemy::Page
@pages = Page.all
else
@pages = Page.accessible_by(current_ability, :index)
end
if params[:page_layout].present?
@pages = @pages.where(page_layout: params[:page_layout])
end
render json: @pages, adapter: :json, root: :pages
end | [
"def",
"index",
"# Fix for cancancan not able to merge multiple AR scopes for logged in users",
"if",
"can?",
":edit_content",
",",
"Alchemy",
"::",
"Page",
"@pages",
"=",
"Page",
".",
"all",
"else",
"@pages",
"=",
"Page",
".",
"accessible_by",
"(",
"current_ability",
",",
":index",
")",
"end",
"if",
"params",
"[",
":page_layout",
"]",
".",
"present?",
"@pages",
"=",
"@pages",
".",
"where",
"(",
"page_layout",
":",
"params",
"[",
":page_layout",
"]",
")",
"end",
"render",
"json",
":",
"@pages",
",",
"adapter",
":",
":json",
",",
"root",
":",
":pages",
"end"
] | Returns all pages as json object | [
"Returns",
"all",
"pages",
"as",
"json",
"object"
] | 0e1c5665984ff67d387c8cb4255f805c296c2fb6 | https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/alchemy/api/pages_controller.rb#L9-L20 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.