id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
15,300
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
15,301
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
15,302
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
15,303
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
15,304
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
15,305
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
15,306
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
15,307
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
15,308
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
15,309
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
15,310
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
15,311
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
15,312
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
15,313
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
15,314
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
15,315
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
15,316
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
15,317
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
15,318
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
15,319
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
15,320
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
15,321
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
15,322
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
15,323
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
15,324
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
15,325
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
15,326
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
15,327
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
15,328
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
15,329
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
15,330
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
15,331
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
15,332
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
15,333
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
15,334
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
15,335
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
15,336
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
15,337
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
15,338
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
15,339
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
15,340
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
15,341
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
15,342
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
15,343
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
15,344
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
15,345
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
15,346
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
15,347
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
15,348
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
15,349
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
15,350
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
15,351
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
15,352
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
15,353
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
15,354
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
15,355
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
15,356
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: !@page.restricted, template: 'pages/show') end
ruby
def render_fresh_page? must_not_cache? || stale?(etag: page_etag, last_modified: @page.published_at, public: !@page.restricted, 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
15,357
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
15,358
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
15,359
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
15,360
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
15,361
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
15,362
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
15,363
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
15,364
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
15,365
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
15,366
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
15,367
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
15,368
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
15,369
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
15,370
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
15,371
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
15,372
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
15,373
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
15,374
AlchemyCMS/alchemy_cms
app/controllers/alchemy/api/pages_controller.rb
Alchemy.Api::PagesController.nested
def nested @page = Page.find_by(id: params[:page_id]) || Language.current_root_page render json: PageTreeSerializer.new(@page, ability: current_ability, user: current_alchemy_user, elements: params[:elements], full: true) end
ruby
def nested @page = Page.find_by(id: params[:page_id]) || Language.current_root_page render json: PageTreeSerializer.new(@page, ability: current_ability, user: current_alchemy_user, elements: params[:elements], full: true) end
[ "def", "nested", "@page", "=", "Page", ".", "find_by", "(", "id", ":", "params", "[", ":page_id", "]", ")", "||", "Language", ".", "current_root_page", "render", "json", ":", "PageTreeSerializer", ".", "new", "(", "@page", ",", "ability", ":", "current_ability", ",", "user", ":", "current_alchemy_user", ",", "elements", ":", "params", "[", ":elements", "]", ",", "full", ":", "true", ")", "end" ]
Returns all pages as nested json object for tree views Pass a page_id param to only load tree for this page Pass elements=true param to include elements for pages
[ "Returns", "all", "pages", "as", "nested", "json", "object", "for", "tree", "views" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/alchemy/api/pages_controller.rb#L28-L36
15,375
AlchemyCMS/alchemy_cms
app/controllers/alchemy/api/elements_controller.rb
Alchemy.Api::ElementsController.index
def index @elements = Element.not_nested # Fix for cancancan not able to merge multiple AR scopes for logged in users if cannot? :manage, Alchemy::Element @elements = @elements.accessible_by(current_ability, :index) end if params[:page_id].present? @elements = @elements.where(page_id: params[:page_id]) end if params[:named].present? @elements = @elements.named(params[:named]) end render json: @elements, adapter: :json, root: :elements end
ruby
def index @elements = Element.not_nested # Fix for cancancan not able to merge multiple AR scopes for logged in users if cannot? :manage, Alchemy::Element @elements = @elements.accessible_by(current_ability, :index) end if params[:page_id].present? @elements = @elements.where(page_id: params[:page_id]) end if params[:named].present? @elements = @elements.named(params[:named]) end render json: @elements, adapter: :json, root: :elements end
[ "def", "index", "@elements", "=", "Element", ".", "not_nested", "# Fix for cancancan not able to merge multiple AR scopes for logged in users", "if", "cannot?", ":manage", ",", "Alchemy", "::", "Element", "@elements", "=", "@elements", ".", "accessible_by", "(", "current_ability", ",", ":index", ")", "end", "if", "params", "[", ":page_id", "]", ".", "present?", "@elements", "=", "@elements", ".", "where", "(", "page_id", ":", "params", "[", ":page_id", "]", ")", "end", "if", "params", "[", ":named", "]", ".", "present?", "@elements", "=", "@elements", ".", "named", "(", "params", "[", ":named", "]", ")", "end", "render", "json", ":", "@elements", ",", "adapter", ":", ":json", ",", "root", ":", ":elements", "end" ]
Returns all elements as json object You can either load all or only these for :page_id param If you want to only load a specific type of element pass ?named=an_element_name
[ "Returns", "all", "elements", "as", "json", "object" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/alchemy/api/elements_controller.rb#L11-L24
15,376
AlchemyCMS/alchemy_cms
lib/alchemy/configuration_methods.rb
Alchemy.ConfigurationMethods.prefix_locale?
def prefix_locale?(locale = Language.current.code) multi_language? && locale != ::I18n.default_locale.to_s end
ruby
def prefix_locale?(locale = Language.current.code) multi_language? && locale != ::I18n.default_locale.to_s end
[ "def", "prefix_locale?", "(", "locale", "=", "Language", ".", "current", ".", "code", ")", "multi_language?", "&&", "locale", "!=", "::", "I18n", ".", "default_locale", ".", "to_s", "end" ]
Decides if the locale should be prefixed to urls If the current language's locale (or the optionally passed in locale) matches the current I18n.locale then the prefix os omitted. Also, if only one published language exists.
[ "Decides", "if", "the", "locale", "should", "be", "prefixed", "to", "urls" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/configuration_methods.rb#L31-L33
15,377
AlchemyCMS/alchemy_cms
lib/alchemy/modules.rb
Alchemy.Modules.module_definition_for
def module_definition_for(name_or_params) case name_or_params when String alchemy_modules.detect { |m| m['name'] == name_or_params } when Hash name_or_params.stringify_keys! alchemy_modules.detect do |alchemy_module| module_navi = alchemy_module.fetch('navigation', {}) definition_from_mainnavi(module_navi, name_or_params) || definition_from_subnavi(module_navi, name_or_params) end else raise ArgumentError, "Could not find module definition for #{name_or_params}" end end
ruby
def module_definition_for(name_or_params) case name_or_params when String alchemy_modules.detect { |m| m['name'] == name_or_params } when Hash name_or_params.stringify_keys! alchemy_modules.detect do |alchemy_module| module_navi = alchemy_module.fetch('navigation', {}) definition_from_mainnavi(module_navi, name_or_params) || definition_from_subnavi(module_navi, name_or_params) end else raise ArgumentError, "Could not find module definition for #{name_or_params}" end end
[ "def", "module_definition_for", "(", "name_or_params", ")", "case", "name_or_params", "when", "String", "alchemy_modules", ".", "detect", "{", "|", "m", "|", "m", "[", "'name'", "]", "==", "name_or_params", "}", "when", "Hash", "name_or_params", ".", "stringify_keys!", "alchemy_modules", ".", "detect", "do", "|", "alchemy_module", "|", "module_navi", "=", "alchemy_module", ".", "fetch", "(", "'navigation'", ",", "{", "}", ")", "definition_from_mainnavi", "(", "module_navi", ",", "name_or_params", ")", "||", "definition_from_subnavi", "(", "module_navi", ",", "name_or_params", ")", "end", "else", "raise", "ArgumentError", ",", "\"Could not find module definition for #{name_or_params}\"", "end", "end" ]
Get the module definition for given module name You can also pass a hash of an module definition. It then tries to find the module defintion from controller name and action name
[ "Get", "the", "module", "definition", "for", "given", "module", "name" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/modules.rb#L66-L80
15,378
AlchemyCMS/alchemy_cms
app/controllers/alchemy/api/contents_controller.rb
Alchemy.Api::ContentsController.index
def index # Fix for cancancan not able to merge multiple AR scopes for logged in users if can? :manage, Alchemy::Content @contents = Content.all else @contents = Content.accessible_by(current_ability, :index) end if params[:element_id].present? @contents = @contents.where(element_id: params[:element_id]) end render json: @contents, adapter: :json, root: :contents end
ruby
def index # Fix for cancancan not able to merge multiple AR scopes for logged in users if can? :manage, Alchemy::Content @contents = Content.all else @contents = Content.accessible_by(current_ability, :index) end if params[:element_id].present? @contents = @contents.where(element_id: params[:element_id]) end render json: @contents, adapter: :json, root: :contents end
[ "def", "index", "# Fix for cancancan not able to merge multiple AR scopes for logged in users", "if", "can?", ":manage", ",", "Alchemy", "::", "Content", "@contents", "=", "Content", ".", "all", "else", "@contents", "=", "Content", ".", "accessible_by", "(", "current_ability", ",", ":index", ")", "end", "if", "params", "[", ":element_id", "]", ".", "present?", "@contents", "=", "@contents", ".", "where", "(", "element_id", ":", "params", "[", ":element_id", "]", ")", "end", "render", "json", ":", "@contents", ",", "adapter", ":", ":json", ",", "root", ":", ":contents", "end" ]
Returns all contents as json object You can either load all or only these for :element_id param
[ "Returns", "all", "contents", "as", "json", "object" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/alchemy/api/contents_controller.rb#L9-L20
15,379
AlchemyCMS/alchemy_cms
app/controllers/alchemy/api/contents_controller.rb
Alchemy.Api::ContentsController.show
def show if params[:id] @content = Content.find(params[:id]) elsif params[:element_id] && params[:name] @content = Content.find_by!(element_id: params[:element_id], name: params[:name]) end authorize! :show, @content respond_with @content end
ruby
def show if params[:id] @content = Content.find(params[:id]) elsif params[:element_id] && params[:name] @content = Content.find_by!(element_id: params[:element_id], name: params[:name]) end authorize! :show, @content respond_with @content end
[ "def", "show", "if", "params", "[", ":id", "]", "@content", "=", "Content", ".", "find", "(", "params", "[", ":id", "]", ")", "elsif", "params", "[", ":element_id", "]", "&&", "params", "[", ":name", "]", "@content", "=", "Content", ".", "find_by!", "(", "element_id", ":", "params", "[", ":element_id", "]", ",", "name", ":", "params", "[", ":name", "]", ")", "end", "authorize!", ":show", ",", "@content", "respond_with", "@content", "end" ]
Returns a json object for content You can either load it from :id param or even more useful via passing the element id and the name of the content $ bin/rake routes for more infos on how the url looks like.
[ "Returns", "a", "json", "object", "for", "content" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/alchemy/api/contents_controller.rb#L31-L39
15,380
AlchemyCMS/alchemy_cms
app/models/alchemy/site.rb
Alchemy.Site.create_default_language!
def create_default_language! default_language = Alchemy::Config.get(:default_language) if default_language languages.build( name: default_language['name'], language_code: default_language['code'], locale: default_language['code'], frontpage_name: default_language['frontpage_name'], page_layout: default_language['page_layout'], public: true, default: true ) else raise DefaultLanguageNotFoundError end end
ruby
def create_default_language! default_language = Alchemy::Config.get(:default_language) if default_language languages.build( name: default_language['name'], language_code: default_language['code'], locale: default_language['code'], frontpage_name: default_language['frontpage_name'], page_layout: default_language['page_layout'], public: true, default: true ) else raise DefaultLanguageNotFoundError end end
[ "def", "create_default_language!", "default_language", "=", "Alchemy", "::", "Config", ".", "get", "(", ":default_language", ")", "if", "default_language", "languages", ".", "build", "(", "name", ":", "default_language", "[", "'name'", "]", ",", "language_code", ":", "default_language", "[", "'code'", "]", ",", "locale", ":", "default_language", "[", "'code'", "]", ",", "frontpage_name", ":", "default_language", "[", "'frontpage_name'", "]", ",", "page_layout", ":", "default_language", "[", "'page_layout'", "]", ",", "public", ":", "true", ",", "default", ":", "true", ")", "else", "raise", "DefaultLanguageNotFoundError", "end", "end" ]
If no languages are present, create a default language based on the host app's Alchemy configuration.
[ "If", "no", "languages", "are", "present", "create", "a", "default", "language", "based", "on", "the", "host", "app", "s", "Alchemy", "configuration", "." ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/site.rb#L101-L116
15,381
AlchemyCMS/alchemy_cms
app/helpers/alchemy/url_helper.rb
Alchemy.UrlHelper.show_page_path_params
def show_page_path_params(page, optional_params = {}) raise ArgumentError, 'Page is nil' if page.nil? url_params = {urlname: page.urlname}.update(optional_params) prefix_locale? ? url_params.update(locale: page.language_code) : url_params end
ruby
def show_page_path_params(page, optional_params = {}) raise ArgumentError, 'Page is nil' if page.nil? url_params = {urlname: page.urlname}.update(optional_params) prefix_locale? ? url_params.update(locale: page.language_code) : url_params end
[ "def", "show_page_path_params", "(", "page", ",", "optional_params", "=", "{", "}", ")", "raise", "ArgumentError", ",", "'Page is nil'", "if", "page", ".", "nil?", "url_params", "=", "{", "urlname", ":", "page", ".", "urlname", "}", ".", "update", "(", "optional_params", ")", "prefix_locale?", "?", "url_params", ".", "update", "(", "locale", ":", "page", ".", "language_code", ")", ":", "url_params", "end" ]
Returns the correct params-hash for passing to show_page_path
[ "Returns", "the", "correct", "params", "-", "hash", "for", "passing", "to", "show_page_path" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/url_helper.rb#L20-L24
15,382
AlchemyCMS/alchemy_cms
app/controllers/concerns/alchemy/page_redirects.rb
Alchemy.PageRedirects.page_redirect_url
def page_redirect_url(options = {}) options = { locale: prefix_locale? ? @page.language_code : nil, urlname: @page.urlname }.merge(options) alchemy.show_page_path additional_params.merge(options) end
ruby
def page_redirect_url(options = {}) options = { locale: prefix_locale? ? @page.language_code : nil, urlname: @page.urlname }.merge(options) alchemy.show_page_path additional_params.merge(options) end
[ "def", "page_redirect_url", "(", "options", "=", "{", "}", ")", "options", "=", "{", "locale", ":", "prefix_locale?", "?", "@page", ".", "language_code", ":", "nil", ",", "urlname", ":", "@page", ".", "urlname", "}", ".", "merge", "(", "options", ")", "alchemy", ".", "show_page_path", "additional_params", ".", "merge", "(", "options", ")", "end" ]
Page url with or without locale while keeping all additional params
[ "Page", "url", "with", "or", "without", "locale", "while", "keeping", "all", "additional", "params" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/concerns/alchemy/page_redirects.rb#L58-L65
15,383
tandusrl/acts_as_bookable
lib/acts_as_bookable/bookable.rb
ActsAsBookable.Bookable.bookable
def bookable(options) if bookable? self.booking_opts = options else class_attribute :booking_opts self.booking_opts = options class_eval do serialize :schedule, IceCube::Schedule has_many :bookings, as: :bookable, dependent: :destroy, class_name: '::ActsAsBookable::Booking' validates_presence_of :schedule, if: :schedule_required? validates_presence_of :capacity, if: :capacity_required? validates_numericality_of :capacity, if: :capacity_required?, only_integer: true, greater_than_or_equal_to: 0 def self.bookable? true end def schedule_required? self.booking_opts && self.booking_opts && self.booking_opts[:time_type] != :none end def capacity_required? self.booking_opts && self.booking_opts[:capacity_type] != :none end end end include Core end
ruby
def bookable(options) if bookable? self.booking_opts = options else class_attribute :booking_opts self.booking_opts = options class_eval do serialize :schedule, IceCube::Schedule has_many :bookings, as: :bookable, dependent: :destroy, class_name: '::ActsAsBookable::Booking' validates_presence_of :schedule, if: :schedule_required? validates_presence_of :capacity, if: :capacity_required? validates_numericality_of :capacity, if: :capacity_required?, only_integer: true, greater_than_or_equal_to: 0 def self.bookable? true end def schedule_required? self.booking_opts && self.booking_opts && self.booking_opts[:time_type] != :none end def capacity_required? self.booking_opts && self.booking_opts[:capacity_type] != :none end end end include Core end
[ "def", "bookable", "(", "options", ")", "if", "bookable?", "self", ".", "booking_opts", "=", "options", "else", "class_attribute", ":booking_opts", "self", ".", "booking_opts", "=", "options", "class_eval", "do", "serialize", ":schedule", ",", "IceCube", "::", "Schedule", "has_many", ":bookings", ",", "as", ":", ":bookable", ",", "dependent", ":", ":destroy", ",", "class_name", ":", "'::ActsAsBookable::Booking'", "validates_presence_of", ":schedule", ",", "if", ":", ":schedule_required?", "validates_presence_of", ":capacity", ",", "if", ":", ":capacity_required?", "validates_numericality_of", ":capacity", ",", "if", ":", ":capacity_required?", ",", "only_integer", ":", "true", ",", "greater_than_or_equal_to", ":", "0", "def", "self", ".", "bookable?", "true", "end", "def", "schedule_required?", "self", ".", "booking_opts", "&&", "self", ".", "booking_opts", "&&", "self", ".", "booking_opts", "[", ":time_type", "]", "!=", ":none", "end", "def", "capacity_required?", "self", ".", "booking_opts", "&&", "self", ".", "booking_opts", "[", ":capacity_type", "]", "!=", ":none", "end", "end", "end", "include", "Core", "end" ]
Make a model bookable
[ "Make", "a", "model", "bookable" ]
45b78114e1a5dab96e59fc70933277a56f65b53b
https://github.com/tandusrl/acts_as_bookable/blob/45b78114e1a5dab96e59fc70933277a56f65b53b/lib/acts_as_bookable/bookable.rb#L22-L54
15,384
tandusrl/acts_as_bookable
lib/acts_as_bookable/booking.rb
ActsAsBookable.Booking.bookable_must_be_bookable
def bookable_must_be_bookable if bookable.present? && !bookable.class.bookable? errors.add(:bookable, T.er('booking.bookable_must_be_bookable', model: bookable.class.to_s)) end end
ruby
def bookable_must_be_bookable if bookable.present? && !bookable.class.bookable? errors.add(:bookable, T.er('booking.bookable_must_be_bookable', model: bookable.class.to_s)) end end
[ "def", "bookable_must_be_bookable", "if", "bookable", ".", "present?", "&&", "!", "bookable", ".", "class", ".", "bookable?", "errors", ".", "add", "(", ":bookable", ",", "T", ".", "er", "(", "'booking.bookable_must_be_bookable'", ",", "model", ":", "bookable", ".", "class", ".", "to_s", ")", ")", "end", "end" ]
Validation method. Check if the bookable resource is actually bookable
[ "Validation", "method", ".", "Check", "if", "the", "bookable", "resource", "is", "actually", "bookable" ]
45b78114e1a5dab96e59fc70933277a56f65b53b
https://github.com/tandusrl/acts_as_bookable/blob/45b78114e1a5dab96e59fc70933277a56f65b53b/lib/acts_as_bookable/booking.rb#L39-L43
15,385
tandusrl/acts_as_bookable
lib/acts_as_bookable/booking.rb
ActsAsBookable.Booking.booker_must_be_booker
def booker_must_be_booker if booker.present? && !booker.class.booker? errors.add(:booker, T.er('booking.booker_must_be_booker', model: booker.class.to_s)) end end
ruby
def booker_must_be_booker if booker.present? && !booker.class.booker? errors.add(:booker, T.er('booking.booker_must_be_booker', model: booker.class.to_s)) end end
[ "def", "booker_must_be_booker", "if", "booker", ".", "present?", "&&", "!", "booker", ".", "class", ".", "booker?", "errors", ".", "add", "(", ":booker", ",", "T", ".", "er", "(", "'booking.booker_must_be_booker'", ",", "model", ":", "booker", ".", "class", ".", "to_s", ")", ")", "end", "end" ]
Validation method. Check if the booker model is actually a booker
[ "Validation", "method", ".", "Check", "if", "the", "booker", "model", "is", "actually", "a", "booker" ]
45b78114e1a5dab96e59fc70933277a56f65b53b
https://github.com/tandusrl/acts_as_bookable/blob/45b78114e1a5dab96e59fc70933277a56f65b53b/lib/acts_as_bookable/booking.rb#L48-L52
15,386
strongqa/howitzer
lib/howitzer/capybara_helpers.rb
Howitzer.CapybaraHelpers.cloud_driver
def cloud_driver(app, caps, url) http_client = ::Selenium::WebDriver::Remote::Http::Default.new http_client.read_timeout = Howitzer.cloud_http_idle_timeout http_client.open_timeout = Howitzer.cloud_http_idle_timeout options = { url: url, desired_capabilities: ::Selenium::WebDriver::Remote::Capabilities.new(caps), http_client: http_client, browser: :remote } driver = Capybara::Selenium::Driver.new(app, options) driver.browser.file_detector = remote_file_detector driver end
ruby
def cloud_driver(app, caps, url) http_client = ::Selenium::WebDriver::Remote::Http::Default.new http_client.read_timeout = Howitzer.cloud_http_idle_timeout http_client.open_timeout = Howitzer.cloud_http_idle_timeout options = { url: url, desired_capabilities: ::Selenium::WebDriver::Remote::Capabilities.new(caps), http_client: http_client, browser: :remote } driver = Capybara::Selenium::Driver.new(app, options) driver.browser.file_detector = remote_file_detector driver end
[ "def", "cloud_driver", "(", "app", ",", "caps", ",", "url", ")", "http_client", "=", "::", "Selenium", "::", "WebDriver", "::", "Remote", "::", "Http", "::", "Default", ".", "new", "http_client", ".", "read_timeout", "=", "Howitzer", ".", "cloud_http_idle_timeout", "http_client", ".", "open_timeout", "=", "Howitzer", ".", "cloud_http_idle_timeout", "options", "=", "{", "url", ":", "url", ",", "desired_capabilities", ":", "::", "Selenium", "::", "WebDriver", "::", "Remote", "::", "Capabilities", ".", "new", "(", "caps", ")", ",", "http_client", ":", "http_client", ",", "browser", ":", ":remote", "}", "driver", "=", "Capybara", "::", "Selenium", "::", "Driver", ".", "new", "(", "app", ",", "options", ")", "driver", ".", "browser", ".", "file_detector", "=", "remote_file_detector", "driver", "end" ]
Buids selenium driver for a cloud service @param app [<Rack>] a rack application that this server will contain @param caps [Hash] remote capabilities @param url [String] a remote hub url @return [Capybara::Selenium::Driver]
[ "Buids", "selenium", "driver", "for", "a", "cloud", "service" ]
fb4d57932e1589cca5254fffc2ac2e57c6e74477
https://github.com/strongqa/howitzer/blob/fb4d57932e1589cca5254fffc2ac2e57c6e74477/lib/howitzer/capybara_helpers.rb#L118-L132
15,387
kontena/k8s-client
lib/k8s/logging.rb
K8s.Logging.logger!
def logger!(progname: self.class.name, target: LOG_TARGET, level: nil, debug: false) @logger = Logger.new(target).tap do |logger| level = Logger::DEBUG if debug logger.progname = "#{self.class.name}<#{progname}>" logger.level = level || self.class.log_level || K8s::Logging.log_level || LOG_LEVEL end end
ruby
def logger!(progname: self.class.name, target: LOG_TARGET, level: nil, debug: false) @logger = Logger.new(target).tap do |logger| level = Logger::DEBUG if debug logger.progname = "#{self.class.name}<#{progname}>" logger.level = level || self.class.log_level || K8s::Logging.log_level || LOG_LEVEL end end
[ "def", "logger!", "(", "progname", ":", "self", ".", "class", ".", "name", ",", "target", ":", "LOG_TARGET", ",", "level", ":", "nil", ",", "debug", ":", "false", ")", "@logger", "=", "Logger", ".", "new", "(", "target", ")", ".", "tap", "do", "|", "logger", "|", "level", "=", "Logger", "::", "DEBUG", "if", "debug", "logger", ".", "progname", "=", "\"#{self.class.name}<#{progname}>\"", "logger", ".", "level", "=", "level", "||", "self", ".", "class", ".", "log_level", "||", "K8s", "::", "Logging", ".", "log_level", "||", "LOG_LEVEL", "end", "end" ]
Use per-instance logger instead of the default per-class logger Sets the instance variable returned by #logger @return [Logger]
[ "Use", "per", "-", "instance", "logger", "instead", "of", "the", "default", "per", "-", "class", "logger" ]
efa19f43202a5d8840084a804afb936a57dc5bdd
https://github.com/kontena/k8s-client/blob/efa19f43202a5d8840084a804afb936a57dc5bdd/lib/k8s/logging.rb#L73-L80
15,388
kontena/k8s-client
lib/k8s/stack.rb
K8s.Stack.prune
def prune(client, keep_resources:, skip_forbidden: true) # using skip_forbidden: assume we can't create resource types that we are forbidden to list, so we don't need to prune them either client.list_resources(labelSelector: { @label => name }, skip_forbidden: skip_forbidden).sort do |a, b| # Sort resources so that namespaced objects are deleted first if a.metadata.namespace == b.metadata.namespace 0 elsif a.metadata.namespace.nil? && !b.metadata.namespace.nil? 1 else -1 end end.each do |resource| next if PRUNE_IGNORE.include? "#{resource.apiVersion}:#{resource.kind}" resource_label = resource.metadata.labels ? resource.metadata.labels[@label] : nil resource_checksum = resource.metadata.annotations ? resource.metadata.annotations[@checksum_annotation] : nil logger.debug { "List resource #{resource.apiVersion}:#{resource.kind}/#{resource.metadata.name} in namespace #{resource.metadata.namespace} with checksum=#{resource_checksum}" } if resource_label != name # apiserver did not respect labelSelector elsif keep_resources && keep_resource?(resource) # resource is up-to-date else logger.info "Delete resource #{resource.apiVersion}:#{resource.kind}/#{resource.metadata.name} in namespace #{resource.metadata.namespace}" begin client.delete_resource(resource, propagationPolicy: 'Background') rescue K8s::Error::NotFound => e # assume aliased objects in multiple API groups, like for Deployments # alternatively, a custom resource whose definition was already deleted earlier logger.debug { "Ignoring #{e} : #{e.message}" } end end end end
ruby
def prune(client, keep_resources:, skip_forbidden: true) # using skip_forbidden: assume we can't create resource types that we are forbidden to list, so we don't need to prune them either client.list_resources(labelSelector: { @label => name }, skip_forbidden: skip_forbidden).sort do |a, b| # Sort resources so that namespaced objects are deleted first if a.metadata.namespace == b.metadata.namespace 0 elsif a.metadata.namespace.nil? && !b.metadata.namespace.nil? 1 else -1 end end.each do |resource| next if PRUNE_IGNORE.include? "#{resource.apiVersion}:#{resource.kind}" resource_label = resource.metadata.labels ? resource.metadata.labels[@label] : nil resource_checksum = resource.metadata.annotations ? resource.metadata.annotations[@checksum_annotation] : nil logger.debug { "List resource #{resource.apiVersion}:#{resource.kind}/#{resource.metadata.name} in namespace #{resource.metadata.namespace} with checksum=#{resource_checksum}" } if resource_label != name # apiserver did not respect labelSelector elsif keep_resources && keep_resource?(resource) # resource is up-to-date else logger.info "Delete resource #{resource.apiVersion}:#{resource.kind}/#{resource.metadata.name} in namespace #{resource.metadata.namespace}" begin client.delete_resource(resource, propagationPolicy: 'Background') rescue K8s::Error::NotFound => e # assume aliased objects in multiple API groups, like for Deployments # alternatively, a custom resource whose definition was already deleted earlier logger.debug { "Ignoring #{e} : #{e.message}" } end end end end
[ "def", "prune", "(", "client", ",", "keep_resources", ":", ",", "skip_forbidden", ":", "true", ")", "# using skip_forbidden: assume we can't create resource types that we are forbidden to list, so we don't need to prune them either", "client", ".", "list_resources", "(", "labelSelector", ":", "{", "@label", "=>", "name", "}", ",", "skip_forbidden", ":", "skip_forbidden", ")", ".", "sort", "do", "|", "a", ",", "b", "|", "# Sort resources so that namespaced objects are deleted first", "if", "a", ".", "metadata", ".", "namespace", "==", "b", ".", "metadata", ".", "namespace", "0", "elsif", "a", ".", "metadata", ".", "namespace", ".", "nil?", "&&", "!", "b", ".", "metadata", ".", "namespace", ".", "nil?", "1", "else", "-", "1", "end", "end", ".", "each", "do", "|", "resource", "|", "next", "if", "PRUNE_IGNORE", ".", "include?", "\"#{resource.apiVersion}:#{resource.kind}\"", "resource_label", "=", "resource", ".", "metadata", ".", "labels", "?", "resource", ".", "metadata", ".", "labels", "[", "@label", "]", ":", "nil", "resource_checksum", "=", "resource", ".", "metadata", ".", "annotations", "?", "resource", ".", "metadata", ".", "annotations", "[", "@checksum_annotation", "]", ":", "nil", "logger", ".", "debug", "{", "\"List resource #{resource.apiVersion}:#{resource.kind}/#{resource.metadata.name} in namespace #{resource.metadata.namespace} with checksum=#{resource_checksum}\"", "}", "if", "resource_label", "!=", "name", "# apiserver did not respect labelSelector", "elsif", "keep_resources", "&&", "keep_resource?", "(", "resource", ")", "# resource is up-to-date", "else", "logger", ".", "info", "\"Delete resource #{resource.apiVersion}:#{resource.kind}/#{resource.metadata.name} in namespace #{resource.metadata.namespace}\"", "begin", "client", ".", "delete_resource", "(", "resource", ",", "propagationPolicy", ":", "'Background'", ")", "rescue", "K8s", "::", "Error", "::", "NotFound", "=>", "e", "# assume aliased objects in multiple API groups, like for Deployments", "# alternatively, a custom resource whose definition was already deleted earlier", "logger", ".", "debug", "{", "\"Ignoring #{e} : #{e.message}\"", "}", "end", "end", "end", "end" ]
Delete all stack resources that were not applied @param client [K8s::Client] @param keep_resources [NilClass, Boolean] @param skip_forbidden [Boolean]
[ "Delete", "all", "stack", "resources", "that", "were", "not", "applied" ]
efa19f43202a5d8840084a804afb936a57dc5bdd
https://github.com/kontena/k8s-client/blob/efa19f43202a5d8840084a804afb936a57dc5bdd/lib/k8s/stack.rb#L139-L173
15,389
kontena/k8s-client
lib/k8s/client.rb
K8s.Client.get_resources
def get_resources(resources) # prefetch api resources, skip missing APIs resource_apis = apis(resources.map(&:apiVersion), prefetch_resources: true, skip_missing: true) # map each resource to excon request options, or nil if resource is not (yet) defined requests = resources.zip(resource_apis).map{ |resource, api_client| next nil unless api_client.api_resources? resource_client = api_client.client_for_resource(resource) { method: 'GET', path: resource_client.path(resource.metadata.name, namespace: resource.metadata.namespace), response_class: resource_client.resource_class } } # map non-nil requests to response objects, or nil for nil request options Util.compact_map(requests) { |reqs| @transport.requests(*reqs, skip_missing: true) } end
ruby
def get_resources(resources) # prefetch api resources, skip missing APIs resource_apis = apis(resources.map(&:apiVersion), prefetch_resources: true, skip_missing: true) # map each resource to excon request options, or nil if resource is not (yet) defined requests = resources.zip(resource_apis).map{ |resource, api_client| next nil unless api_client.api_resources? resource_client = api_client.client_for_resource(resource) { method: 'GET', path: resource_client.path(resource.metadata.name, namespace: resource.metadata.namespace), response_class: resource_client.resource_class } } # map non-nil requests to response objects, or nil for nil request options Util.compact_map(requests) { |reqs| @transport.requests(*reqs, skip_missing: true) } end
[ "def", "get_resources", "(", "resources", ")", "# prefetch api resources, skip missing APIs", "resource_apis", "=", "apis", "(", "resources", ".", "map", "(", ":apiVersion", ")", ",", "prefetch_resources", ":", "true", ",", "skip_missing", ":", "true", ")", "# map each resource to excon request options, or nil if resource is not (yet) defined", "requests", "=", "resources", ".", "zip", "(", "resource_apis", ")", ".", "map", "{", "|", "resource", ",", "api_client", "|", "next", "nil", "unless", "api_client", ".", "api_resources?", "resource_client", "=", "api_client", ".", "client_for_resource", "(", "resource", ")", "{", "method", ":", "'GET'", ",", "path", ":", "resource_client", ".", "path", "(", "resource", ".", "metadata", ".", "name", ",", "namespace", ":", "resource", ".", "metadata", ".", "namespace", ")", ",", "response_class", ":", "resource_client", ".", "resource_class", "}", "}", "# map non-nil requests to response objects, or nil for nil request options", "Util", ".", "compact_map", "(", "requests", ")", "{", "|", "reqs", "|", "@transport", ".", "requests", "(", "reqs", ",", "skip_missing", ":", "true", ")", "}", "end" ]
Returns nils for any resources that do not exist. This includes custom resources that were not yet defined. @param resources [Array<K8s::Resource>] @return [Array<K8s::Resource, nil>] matching resources array 1:1
[ "Returns", "nils", "for", "any", "resources", "that", "do", "not", "exist", ".", "This", "includes", "custom", "resources", "that", "were", "not", "yet", "defined", "." ]
efa19f43202a5d8840084a804afb936a57dc5bdd
https://github.com/kontena/k8s-client/blob/efa19f43202a5d8840084a804afb936a57dc5bdd/lib/k8s/client.rb#L232-L253
15,390
Shopify/active_shipping
lib/active_shipping/carriers/fedex.rb
ActiveShipping.FedEx.create_shipment
def create_shipment(origin, destination, packages, options = {}) options = @options.merge(options) packages = Array(packages) raise Error, "Multiple packages are not supported yet." if packages.length > 1 request = build_shipment_request(origin, destination, packages, options) logger.debug(request) if logger response = commit(save_request(request), (options[:test] || false)) parse_ship_response(response) end
ruby
def create_shipment(origin, destination, packages, options = {}) options = @options.merge(options) packages = Array(packages) raise Error, "Multiple packages are not supported yet." if packages.length > 1 request = build_shipment_request(origin, destination, packages, options) logger.debug(request) if logger response = commit(save_request(request), (options[:test] || false)) parse_ship_response(response) end
[ "def", "create_shipment", "(", "origin", ",", "destination", ",", "packages", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "packages", "=", "Array", "(", "packages", ")", "raise", "Error", ",", "\"Multiple packages are not supported yet.\"", "if", "packages", ".", "length", ">", "1", "request", "=", "build_shipment_request", "(", "origin", ",", "destination", ",", "packages", ",", "options", ")", "logger", ".", "debug", "(", "request", ")", "if", "logger", "response", "=", "commit", "(", "save_request", "(", "request", ")", ",", "(", "options", "[", ":test", "]", "||", "false", ")", ")", "parse_ship_response", "(", "response", ")", "end" ]
Get Shipping labels
[ "Get", "Shipping", "labels" ]
590bc805e10a137251c122a1525940c34b164a44
https://github.com/Shopify/active_shipping/blob/590bc805e10a137251c122a1525940c34b164a44/lib/active_shipping/carriers/fedex.rb#L175-L185
15,391
Shopify/active_shipping
lib/active_shipping/carrier.rb
ActiveShipping.Carrier.timestamp_from_business_day
def timestamp_from_business_day(days) return unless days date = DateTime.now.utc days.times do date += 1.day date += 2.days if date.saturday? date += 1.day if date.sunday? end date.to_datetime end
ruby
def timestamp_from_business_day(days) return unless days date = DateTime.now.utc days.times do date += 1.day date += 2.days if date.saturday? date += 1.day if date.sunday? end date.to_datetime end
[ "def", "timestamp_from_business_day", "(", "days", ")", "return", "unless", "days", "date", "=", "DateTime", ".", "now", ".", "utc", "days", ".", "times", "do", "date", "+=", "1", ".", "day", "date", "+=", "2", ".", "days", "if", "date", ".", "saturday?", "date", "+=", "1", ".", "day", "if", "date", ".", "sunday?", "end", "date", ".", "to_datetime", "end" ]
Calculates a timestamp that corresponds a given number of business days in the future @param days [Integer] The number of business days from now. @return [DateTime] A timestamp, the provided number of business days in the future.
[ "Calculates", "a", "timestamp", "that", "corresponds", "a", "given", "number", "of", "business", "days", "in", "the", "future" ]
590bc805e10a137251c122a1525940c34b164a44
https://github.com/Shopify/active_shipping/blob/590bc805e10a137251c122a1525940c34b164a44/lib/active_shipping/carrier.rb#L170-L182
15,392
Shopify/active_shipping
lib/active_shipping/rate_estimate.rb
ActiveShipping.RateEstimate.add
def add(package, rate = nil) cents = Package.cents_from(rate) raise ArgumentError.new("New packages must have valid rate information since this RateEstimate has no total_price set.") if cents.nil? and total_price.nil? @package_rates << {:package => package, :rate => cents} self end
ruby
def add(package, rate = nil) cents = Package.cents_from(rate) raise ArgumentError.new("New packages must have valid rate information since this RateEstimate has no total_price set.") if cents.nil? and total_price.nil? @package_rates << {:package => package, :rate => cents} self end
[ "def", "add", "(", "package", ",", "rate", "=", "nil", ")", "cents", "=", "Package", ".", "cents_from", "(", "rate", ")", "raise", "ArgumentError", ".", "new", "(", "\"New packages must have valid rate information since this RateEstimate has no total_price set.\"", ")", "if", "cents", ".", "nil?", "and", "total_price", ".", "nil?", "@package_rates", "<<", "{", ":package", "=>", "package", ",", ":rate", "=>", "cents", "}", "self", "end" ]
Adds a package to this rate estimate @param package [ActiveShipping::Package] The package to add. @param rate [#cents, Float, String, nil] The rate for this package. This is only required if there is no total price for this shipment @return [self]
[ "Adds", "a", "package", "to", "this", "rate", "estimate" ]
590bc805e10a137251c122a1525940c34b164a44
https://github.com/Shopify/active_shipping/blob/590bc805e10a137251c122a1525940c34b164a44/lib/active_shipping/rate_estimate.rb#L132-L137
15,393
Shopify/active_shipping
lib/active_shipping/carriers/canada_post_pws.rb
ActiveShipping.CanadaPostPWS.create_shipment
def create_shipment(origin, destination, package, line_items = [], options = {}) request_body = build_shipment_request(origin, destination, package, line_items, options) response = ssl_post(create_shipment_url(options), request_body, headers(options, SHIPMENT_MIMETYPE, SHIPMENT_MIMETYPE)) parse_shipment_response(response) rescue ActiveUtils::ResponseError, ActiveShipping::ResponseError => e error_response(e.response.body, CPPWSShippingResponse) rescue MissingCustomerNumberError CPPWSShippingResponse.new(false, "Missing Customer Number", {}, :carrier => @@name) end
ruby
def create_shipment(origin, destination, package, line_items = [], options = {}) request_body = build_shipment_request(origin, destination, package, line_items, options) response = ssl_post(create_shipment_url(options), request_body, headers(options, SHIPMENT_MIMETYPE, SHIPMENT_MIMETYPE)) parse_shipment_response(response) rescue ActiveUtils::ResponseError, ActiveShipping::ResponseError => e error_response(e.response.body, CPPWSShippingResponse) rescue MissingCustomerNumberError CPPWSShippingResponse.new(false, "Missing Customer Number", {}, :carrier => @@name) end
[ "def", "create_shipment", "(", "origin", ",", "destination", ",", "package", ",", "line_items", "=", "[", "]", ",", "options", "=", "{", "}", ")", "request_body", "=", "build_shipment_request", "(", "origin", ",", "destination", ",", "package", ",", "line_items", ",", "options", ")", "response", "=", "ssl_post", "(", "create_shipment_url", "(", "options", ")", ",", "request_body", ",", "headers", "(", "options", ",", "SHIPMENT_MIMETYPE", ",", "SHIPMENT_MIMETYPE", ")", ")", "parse_shipment_response", "(", "response", ")", "rescue", "ActiveUtils", "::", "ResponseError", ",", "ActiveShipping", "::", "ResponseError", "=>", "e", "error_response", "(", "e", ".", "response", ".", "body", ",", "CPPWSShippingResponse", ")", "rescue", "MissingCustomerNumberError", "CPPWSShippingResponse", ".", "new", "(", "false", ",", "\"Missing Customer Number\"", ",", "{", "}", ",", ":carrier", "=>", "@@name", ")", "end" ]
line_items should be a list of PackageItem's
[ "line_items", "should", "be", "a", "list", "of", "PackageItem", "s" ]
590bc805e10a137251c122a1525940c34b164a44
https://github.com/Shopify/active_shipping/blob/590bc805e10a137251c122a1525940c34b164a44/lib/active_shipping/carriers/canada_post_pws.rb#L100-L108
15,394
activeadmin-plugins/active_admin_import
lib/active_admin_import/importer.rb
ActiveAdminImport.Importer.batch_slice_columns
def batch_slice_columns(slice_columns) use_indexes = [] headers.values.each_with_index do |val, index| use_indexes << index if val.in?(slice_columns) end return csv_lines if use_indexes.empty? # slice CSV headers @headers = headers.to_a.values_at(*use_indexes).to_h # slice CSV values csv_lines.map! do |line| line.values_at(*use_indexes) end end
ruby
def batch_slice_columns(slice_columns) use_indexes = [] headers.values.each_with_index do |val, index| use_indexes << index if val.in?(slice_columns) end return csv_lines if use_indexes.empty? # slice CSV headers @headers = headers.to_a.values_at(*use_indexes).to_h # slice CSV values csv_lines.map! do |line| line.values_at(*use_indexes) end end
[ "def", "batch_slice_columns", "(", "slice_columns", ")", "use_indexes", "=", "[", "]", "headers", ".", "values", ".", "each_with_index", "do", "|", "val", ",", "index", "|", "use_indexes", "<<", "index", "if", "val", ".", "in?", "(", "slice_columns", ")", "end", "return", "csv_lines", "if", "use_indexes", ".", "empty?", "# slice CSV headers", "@headers", "=", "headers", ".", "to_a", ".", "values_at", "(", "use_indexes", ")", ".", "to_h", "# slice CSV values", "csv_lines", ".", "map!", "do", "|", "line", "|", "line", ".", "values_at", "(", "use_indexes", ")", "end", "end" ]
Use it when CSV file contain redundant columns Example: ActiveAdmin.register Post active_admin_import before_batch_import: lambda { |importer| importer.batch_slice_columns(['name', 'birthday']) } end
[ "Use", "it", "when", "CSV", "file", "contain", "redundant", "columns" ]
7e17eb6f33cdb0329ac98730ab063cd0f31339c9
https://github.com/activeadmin-plugins/active_admin_import/blob/7e17eb6f33cdb0329ac98730ab063cd0f31339c9/lib/active_admin_import/importer.rb#L83-L95
15,395
chriskite/anemone
lib/anemone/page_store.rb
Anemone.PageStore.has_page?
def has_page?(url) schemes = %w(http https) if schemes.include? url.scheme u = url.dup return schemes.any? { |s| u.scheme = s; has_key?(u) } end has_key? url end
ruby
def has_page?(url) schemes = %w(http https) if schemes.include? url.scheme u = url.dup return schemes.any? { |s| u.scheme = s; has_key?(u) } end has_key? url end
[ "def", "has_page?", "(", "url", ")", "schemes", "=", "%w(", "http", "https", ")", "if", "schemes", ".", "include?", "url", ".", "scheme", "u", "=", "url", ".", "dup", "return", "schemes", ".", "any?", "{", "|", "s", "|", "u", ".", "scheme", "=", "s", ";", "has_key?", "(", "u", ")", "}", "end", "has_key?", "url", "end" ]
Does this PageStore contain the specified URL? HTTP and HTTPS versions of a URL are considered to be the same page.
[ "Does", "this", "PageStore", "contain", "the", "specified", "URL?", "HTTP", "and", "HTTPS", "versions", "of", "a", "URL", "are", "considered", "to", "be", "the", "same", "page", "." ]
72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa
https://github.com/chriskite/anemone/blob/72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa/lib/anemone/page_store.rb#L51-L59
15,396
chriskite/anemone
lib/anemone/core.rb
Anemone.Core.run
def run process_options @urls.delete_if { |url| !visit_link?(url) } return if @urls.empty? link_queue = Queue.new page_queue = Queue.new @opts[:threads].times do @tentacles << Thread.new { Tentacle.new(link_queue, page_queue, @opts).run } end @urls.each{ |url| link_queue.enq(url) } loop do page = page_queue.deq @pages.touch_key page.url puts "#{page.url} Queue: #{link_queue.size}" if @opts[:verbose] do_page_blocks page page.discard_doc! if @opts[:discard_page_bodies] links = links_to_follow page links.each do |link| link_queue << [link, page.url.dup, page.depth + 1] end @pages.touch_keys links @pages[page.url] = page # if we are done with the crawl, tell the threads to end if link_queue.empty? and page_queue.empty? until link_queue.num_waiting == @tentacles.size Thread.pass end if page_queue.empty? @tentacles.size.times { link_queue << :END } break end end end @tentacles.each { |thread| thread.join } do_after_crawl_blocks self end
ruby
def run process_options @urls.delete_if { |url| !visit_link?(url) } return if @urls.empty? link_queue = Queue.new page_queue = Queue.new @opts[:threads].times do @tentacles << Thread.new { Tentacle.new(link_queue, page_queue, @opts).run } end @urls.each{ |url| link_queue.enq(url) } loop do page = page_queue.deq @pages.touch_key page.url puts "#{page.url} Queue: #{link_queue.size}" if @opts[:verbose] do_page_blocks page page.discard_doc! if @opts[:discard_page_bodies] links = links_to_follow page links.each do |link| link_queue << [link, page.url.dup, page.depth + 1] end @pages.touch_keys links @pages[page.url] = page # if we are done with the crawl, tell the threads to end if link_queue.empty? and page_queue.empty? until link_queue.num_waiting == @tentacles.size Thread.pass end if page_queue.empty? @tentacles.size.times { link_queue << :END } break end end end @tentacles.each { |thread| thread.join } do_after_crawl_blocks self end
[ "def", "run", "process_options", "@urls", ".", "delete_if", "{", "|", "url", "|", "!", "visit_link?", "(", "url", ")", "}", "return", "if", "@urls", ".", "empty?", "link_queue", "=", "Queue", ".", "new", "page_queue", "=", "Queue", ".", "new", "@opts", "[", ":threads", "]", ".", "times", "do", "@tentacles", "<<", "Thread", ".", "new", "{", "Tentacle", ".", "new", "(", "link_queue", ",", "page_queue", ",", "@opts", ")", ".", "run", "}", "end", "@urls", ".", "each", "{", "|", "url", "|", "link_queue", ".", "enq", "(", "url", ")", "}", "loop", "do", "page", "=", "page_queue", ".", "deq", "@pages", ".", "touch_key", "page", ".", "url", "puts", "\"#{page.url} Queue: #{link_queue.size}\"", "if", "@opts", "[", ":verbose", "]", "do_page_blocks", "page", "page", ".", "discard_doc!", "if", "@opts", "[", ":discard_page_bodies", "]", "links", "=", "links_to_follow", "page", "links", ".", "each", "do", "|", "link", "|", "link_queue", "<<", "[", "link", ",", "page", ".", "url", ".", "dup", ",", "page", ".", "depth", "+", "1", "]", "end", "@pages", ".", "touch_keys", "links", "@pages", "[", "page", ".", "url", "]", "=", "page", "# if we are done with the crawl, tell the threads to end", "if", "link_queue", ".", "empty?", "and", "page_queue", ".", "empty?", "until", "link_queue", ".", "num_waiting", "==", "@tentacles", ".", "size", "Thread", ".", "pass", "end", "if", "page_queue", ".", "empty?", "@tentacles", ".", "size", ".", "times", "{", "link_queue", "<<", ":END", "}", "break", "end", "end", "end", "@tentacles", ".", "each", "{", "|", "thread", "|", "thread", ".", "join", "}", "do_after_crawl_blocks", "self", "end" ]
Perform the crawl
[ "Perform", "the", "crawl" ]
72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa
https://github.com/chriskite/anemone/blob/72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa/lib/anemone/core.rb#L148-L193
15,397
chriskite/anemone
lib/anemone/core.rb
Anemone.Core.freeze_options
def freeze_options @opts.freeze @opts.each_key { |key| @opts[key].freeze } @opts[:cookies].each_key { |key| @opts[:cookies][key].freeze } rescue nil end
ruby
def freeze_options @opts.freeze @opts.each_key { |key| @opts[key].freeze } @opts[:cookies].each_key { |key| @opts[:cookies][key].freeze } rescue nil end
[ "def", "freeze_options", "@opts", ".", "freeze", "@opts", ".", "each_key", "{", "|", "key", "|", "@opts", "[", "key", "]", ".", "freeze", "}", "@opts", "[", ":cookies", "]", ".", "each_key", "{", "|", "key", "|", "@opts", "[", ":cookies", "]", "[", "key", "]", ".", "freeze", "}", "rescue", "nil", "end" ]
Freeze the opts Hash so that no options can be modified once the crawl begins
[ "Freeze", "the", "opts", "Hash", "so", "that", "no", "options", "can", "be", "modified", "once", "the", "crawl", "begins" ]
72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa
https://github.com/chriskite/anemone/blob/72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa/lib/anemone/core.rb#L211-L215
15,398
chriskite/anemone
lib/anemone/http.rb
Anemone.HTTP.allowed?
def allowed?(to_url, from_url) to_url.host.nil? || (to_url.host == from_url.host) end
ruby
def allowed?(to_url, from_url) to_url.host.nil? || (to_url.host == from_url.host) end
[ "def", "allowed?", "(", "to_url", ",", "from_url", ")", "to_url", ".", "host", ".", "nil?", "||", "(", "to_url", ".", "host", "==", "from_url", ".", "host", ")", "end" ]
Allowed to connect to the requested url?
[ "Allowed", "to", "connect", "to", "the", "requested", "url?" ]
72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa
https://github.com/chriskite/anemone/blob/72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa/lib/anemone/http.rb#L182-L184
15,399
chriskite/anemone
lib/anemone/tentacle.rb
Anemone.Tentacle.run
def run loop do link, referer, depth = @link_queue.deq break if link == :END @http.fetch_pages(link, referer, depth).each { |page| @page_queue << page } delay end end
ruby
def run loop do link, referer, depth = @link_queue.deq break if link == :END @http.fetch_pages(link, referer, depth).each { |page| @page_queue << page } delay end end
[ "def", "run", "loop", "do", "link", ",", "referer", ",", "depth", "=", "@link_queue", ".", "deq", "break", "if", "link", "==", ":END", "@http", ".", "fetch_pages", "(", "link", ",", "referer", ",", "depth", ")", ".", "each", "{", "|", "page", "|", "@page_queue", "<<", "page", "}", "delay", "end", "end" ]
Create a new Tentacle Gets links from @link_queue, and returns the fetched Page objects into @page_queue
[ "Create", "a", "new", "Tentacle" ]
72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa
https://github.com/chriskite/anemone/blob/72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa/lib/anemone/tentacle.rb#L20-L30