idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
500 | def allowed_to_promote? ( emendation ) return unless emendation . amendment . rejected? && emendation . created_by? ( current_user ) return if promoted? ( emendation ) true end | Checks if the user can promote the emendation |
501 | def promoted? ( emendation ) logs = Decidim :: ActionLog . where ( decidim_component_id : emendation . component ) . where ( decidim_user_id : emendation . creator_author ) . where ( action : "promote" ) logs . select { | log | log . extra [ "promoted_from" ] == emendation . id } . present? end | Checks if the unique ActionLog created in the promote command exists . |
502 | def user_group_select_field ( form , name ) form . select ( name , current_user . user_groups . verified . map { | g | [ g . name , g . id ] } , selected : form . object . user_group_id . presence , include_blank : current_user . name , label : t ( "new.amendment_author" , scope : "decidim.amendments" ) ) end | Renders a UserGroup select field in a form . |
503 | def emendation_field_value ( form , original , key ) return params [ :amendment ] [ :emendation_params ] [ key ] if params [ :amendment ] . present? present ( form . object . send ( original ) ) . send ( key ) end | Return the edited field value or presents the original attribute value in a form . |
504 | def static_map_link ( resource , options = { } ) return unless resource . geocoded? zoom = options [ :zoom ] || 17 latitude = resource . latitude longitude = resource . longitude map_url = "https://www.openstreetmap.org/?mlat=#{latitude}&mlon=#{longitude}#map=#{zoom}/#{latitude}/#{longitude}" link_to map_url , target : "_blank" do image_tag decidim . static_map_path ( sgid : resource . to_sgid . to_s ) end end | Renders a link to openstreetmaps with the resource latitude and longitude . The link s content is a static map image . |
505 | def attachment_title ( attachment ) attachment . title . is_a? ( Hash ) ? translated_attribute ( attachment . title ) : attachment . title end | Renders the attachment s title . Checks if the attachment s title is translated or not and use the correct render method . |
506 | def submit_tag ( text = "Save changes" , options = { } ) options = options . stringify_keys content_tag :button , text , { "type" => "submit" , "name" => "commit" } . update ( options ) end | Overrides the submit tags to always be buttons instead of inputs . Buttons are much more stylable and less prone to bugs . |
507 | def create ( klass , author , params , extra_log_info = { } ) perform_action! ( :create , klass , author , extra_log_info ) do klass . create ( params ) end end | Calls the create method to the given class and sets the author of the version . |
508 | def create! ( klass , author , params , extra_log_info = { } ) perform_action! ( :create , klass , author , extra_log_info ) do klass . create! ( params ) end end | Calls the create! method to the given class and sets the author of the version . |
509 | def perform_action! ( action , resource , author , extra_log_info = { } ) PaperTrail . request ( whodunnit : gid ( author ) ) do Decidim :: ApplicationRecord . transaction do result = block_given? ? yield : nil loggable_resource = resource . is_a? ( Class ) ? result : resource log ( action , author , loggable_resource , extra_log_info ) return result end end end | Performs the given block and sets the author of the action . It also logs the action with the given action parameter . The action and the logging are run inside a transaction . |
510 | def update! ( resource , author , params , extra_log_info = { } ) perform_action! ( :update , resource , author , extra_log_info ) do resource . update! ( params ) resource end end | Updates the resource with update! and sets the author of the version . |
511 | def html_truncate ( text , options = { } ) options [ :max_length ] = options . delete ( :length ) || options [ :max_length ] options [ :tail ] = options . delete ( :separator ) || options [ :tail ] || "..." options [ :count_tags ] ||= false options [ :count_tail ] ||= false options [ :tail_before_final_tag ] ||= true Truncato . truncate ( text , options ) end | Truncates a given text respecting its HTML tags . |
512 | def edit_link ( link , action , subject , extra_context = { } ) return unless current_user return unless admin_allowed_to? ( action , subject , extra_context ) return if content_for? ( :edit_link ) content_for ( :edit_link , link ) end | Generates a link to be added to the global Edit link so admins can easily manage data without having to look for it at the admin panel when they re at a public page . |
513 | def context ( name = :public , & block ) name = name . to_sym @contexts ||= { } if block context = ParticipatorySpaceContextManifest . new context . instance_eval ( & block ) @contexts [ name ] = context end @contexts . fetch ( name ) end | A context used to set the layout and behavior of a participatory space . Full documentation can be found looking at the ParticipatorySpaceContextManifest class . |
514 | def friendly_created_at current_datetime = Time . current if created_at > current_datetime . beginning_of_day I18n . l ( created_at , format : :time_of_day ) elsif created_at > current_datetime . beginning_of_week I18n . l ( created_at , format : :day_of_week ) elsif created_at > current_datetime . beginning_of_year I18n . l ( created_at , format : :day_of_month ) else I18n . l ( created_at , format : :day_of_year ) end end | Returns the creation date in a friendly relative format . |
515 | def retrieve_participatory_spaces Decidim . participatory_space_manifests . map do | space_manifest | next unless space_manifest . name == :participatory_processes space_manifest . participatory_spaces . call ( @organization ) end . flatten . compact end | Search for all Participatory Space manifests and then all records available Limited to ParticipatoryProcesses only |
516 | def localized_locales ( collection = Decidim . available_locales ) klass = Class . new do def initialize ( locale ) @locale = locale end def id @locale . to_s end def name I18n . with_locale ( @locale ) { I18n . t ( "name" , scope : "locale" ) } end end collection . map { | locale | klass . new ( locale ) } end | Converts a given array of strings to an array of Objects representing locales . |
517 | def call ( env ) organization = detect_current_organization ( env ) if organization env [ "decidim.current_organization" ] = organization @app . call ( env ) else organization = find_secondary_host_org ( env ) return @app . call ( env ) unless organization location = new_location_for ( env , organization . host ) [ 301 , { "Location" => location , "Content-Type" => "text/html" , "Content-Length" => "0" } , [ ] ] end end | Initializes the Rack Middleware . |
518 | def call return broadcast ( :invalid ) unless @form . valid? Decidim :: User . transaction do destroy_user_account! destroy_user_identities destroy_user_group_memberships destroy_follows end broadcast ( :ok ) end | Destroy a user s account . |
519 | def authorize raise AuthorizationError , "Missing data" unless component && action AuthorizationStatusCollection . new ( authorization_handlers , user , component , resource ) end | Initializes the ActionAuthorizer . |
520 | def call return broadcast ( :invalid ) unless @form . valid? update_personal_data update_avatar update_password if @user . valid? @user . save! notify_followers broadcast ( :ok , @user . unconfirmed_email . present? ) else @form . errors . add :avatar , @user . errors [ :avatar ] if @user . errors . has_key? :avatar broadcast ( :invalid ) end end | Updates a user s account . |
521 | def linked_resources_for ( resource , type , link_name ) linked_resources = resource . linked_resources ( type , link_name ) . group_by { | linked_resource | linked_resource . class . name } safe_join ( linked_resources . map do | klass , resources | resource_manifest = klass . constantize . resource_manifest content_tag ( :div , class : "section" ) do i18n_name = "#{resource.class.name.demodulize.underscore}_#{resource_manifest.name}" content_tag ( :h3 , I18n . t ( i18n_name , scope : "decidim.resource_links.#{link_name}" ) , class : "section-heading" ) + render ( partial : resource_manifest . template , locals : { resources : resources } ) end end ) end | Renders a collection of linked resources for a resource . |
522 | def resource_title ( resource ) title = resource . try ( :title ) || resource . try ( :name ) || resource . try ( :subject ) || "#{resource.model_name.human} ##{resource.id}" title = translated_attribute ( title ) if title . is_a? ( Hash ) title end | Returns a descriptive title for the resource |
523 | def decidim_paginate ( collection , paginate_params = { } ) default_params = { participatory_process_id : nil , component_id : nil } paginate collection , theme : "decidim" , params : paginate_params . merge ( default_params ) end | Displays pagination links for the given collection setting the correct theme . This mostly acts as a proxy for the underlying pagination engine . |
524 | def participatory_space_lazy ( cache : true ) return if participatory_space_id . blank? || participatory_space_type . blank? return resouce_lazy if participatory_space_id == resource_id && participatory_space_type == resource_type self . class . lazy_relation ( participatory_space_id , participatory_space_type , cache ) end | Lazy loads the participatory_space association through BatchLoader can be used as a regular object . |
525 | def search_scope_id clean_scope_ids = if scope_id . is_a? ( Hash ) scope_id . values else [ scope_id ] . flatten end conditions = [ ] conditions << "decidim_scope_id IS NULL" if clean_scope_ids . delete ( "global" ) conditions . concat ( [ "? = ANY(decidim_scopes.part_of)" ] * clean_scope_ids . count ) if clean_scope_ids . any? query . includes ( :scope ) . references ( :decidim_scopes ) . where ( conditions . join ( " OR " ) , * clean_scope_ids . map ( & :to_i ) ) end | Handles the scope_id filter . When we want to show only those that do not have a scope_id set we cannot pass an empty String or nil because Searchlight will automatically filter out these params so the method will not be used . Instead we need to pass a fake ID and then convert it inside . In this case in order to select those elements that do not have a scope_id set we use global as parameter and in the method we do the needed changes to search properly . |
526 | def custom_url_for_mail_root ( organization , newsletter_id = nil ) if newsletter_id . present? decidim . root_url ( host : organization . host ) + utm_codes ( organization . host , newsletter_id . to_s ) else decidim . root_url ( host : organization . host ) end end | this method is used to generate the root link on mail with the utm_codes If the newsletter_id is nil it returns the root_url |
527 | def icon ( name , options = { } ) html_properties = { } html_properties [ "width" ] = options [ :width ] html_properties [ "height" ] = options [ :height ] html_properties [ "aria-label" ] = options [ :aria_label ] html_properties [ "role" ] = options [ :role ] html_properties [ "aria-hidden" ] = options [ :aria_hidden ] html_properties [ "class" ] = ( [ "icon--#{name}" ] + _icon_classes ( options ) ) . join ( " " ) content_tag :svg , html_properties do content_tag :use , nil , "xlink:href" => "#{asset_path("decidim/icons.svg")}#icon-#{name}" end end | Outputs an SVG - based icon . |
528 | def external_icon ( path , options = { } ) classes = _icon_classes ( options ) + [ "external-icon" ] if path . split ( "." ) . last == "svg" asset = Rails . application . assets_manifest . find_sources ( path ) . first asset . gsub ( "<svg " , "<svg class=\"#{classes.join(" ")}\" " ) . html_safe else image_tag ( path , class : classes . join ( " " ) , style : "display: none" ) end end | Outputs a SVG icon from an external file . It apparently renders an image tag but then a JS script kicks in and replaces it with an inlined SVG version . |
529 | def track! ( date ) @subject . with_lock do last_session_at = status . try ( :last_session_at ) || date current_streak = status . try ( :current_streak ) || 1 streak = if last_session_at == date current_streak elsif last_session_at == date - 1 . day current_streak + 1 else 1 end update_status ( date , streak ) update_badge ( streak ) end end | Initializes the class with a polymorphic subject |
530 | def invitation_instructions ( user , token , opts = { } ) with_user ( user ) do @token = token @organization = user . organization @opts = opts opts [ :subject ] = I18n . t ( "devise.mailer.#{opts[:invitation_instructions]}.subject" , organization : user . organization . name ) if opts [ :invitation_instructions ] end devise_mail ( user , opts [ :invitation_instructions ] || :invitation_instructions , opts ) end | Sends an email with the invitation instructions to a new user . |
531 | def show return if activities . blank? activities . map do | activity | activity . organization_lazy activity . resource_lazy activity . participatory_space_lazy activity . component_lazy end render end | Since we re rendering each activity separatedly we need to trigger BatchLoader in order to accumulate all the ids to be found later . |
532 | def main_component_path ( component ) current_params = try ( :params ) || { } EngineRouter . main_proxy ( component ) . root_path ( locale : current_params [ :locale ] ) end | Returns the defined root path for a given component . |
533 | def main_component_url ( component ) current_params = try ( :params ) || { } EngineRouter . main_proxy ( component ) . root_url ( locale : current_params [ :locale ] ) end | Returns the defined root url for a given component . |
534 | def manage_component_path ( component ) current_params = try ( :params ) || { } EngineRouter . admin_proxy ( component ) . root_path ( locale : current_params [ :locale ] ) end | Returns the defined admin root path for a given component . |
535 | def searchable_resource_human_name ( resource , count : 5 ) resource = if resource . is_a? ( String ) resource . constantize else resource end resource . model_name . human ( count : count ) end | Renders the human name of the given class name . |
536 | def search_path_by ( resource_type : nil , space_state : nil ) new_params = { utf8 : params [ :utf8 ] , filter : { decidim_scope_id : params . dig ( :filter , :decidim_scope_id ) , term : params [ :term ] || params . dig ( :filter , :term ) } } new_params [ :filter ] [ :resource_type ] = resource_type if resource_type . present? new_params [ :filter ] [ :space_state ] = space_state if space_state . present? decidim . search_path ( new_params ) end | Generates a link to filter the current search by the given type . If no type is given it generates a link to the main results page . |
537 | def search_path_by_state_link ( state ) path = search_path_by ( resource_type : params . dig ( :filter , :resource_type ) , space_state : state ) is_active = params . dig ( :filter , :space_state ) . to_s == state . to_s link_to path , class : "order-by__tab#{" is-active" if is_active}" do content_tag ( :strong , t ( state || :all , scope : "decidim.searches.filters.state" ) ) end end | Generates the path and link to filter by space state taking into account the other filters applied . |
538 | def decidim_form_for ( record , options = { } , & block ) options [ :data ] ||= { } options [ :data ] . update ( abide : true , "live-validate" => true , "validate-on-blur" => true ) options [ :html ] ||= { } options [ :html ] . update ( novalidate : true ) output = "" output += base_error_messages ( record ) . to_s output += form_for ( record , options , & block ) . to_s output . html_safe end | A custom form for that injects client side validations with Abide . |
539 | def editor_field_tag ( name , value , options = { } ) options [ :toolbar ] ||= "basic" options [ :lines ] ||= 10 content_tag ( :div , class : "editor" ) do template = "" template += label_tag ( name , options [ :label ] ) if options [ :label ] != false template += hidden_field_tag ( name , value , options ) template += content_tag ( :div , nil , class : "editor-container" , data : { toolbar : options [ :toolbar ] } , style : "height: #{options[:lines]}rem" ) template . html_safe end end | A custom helper to include an editor field without requiring a form object |
540 | def scopes_picker_field_tag ( name , value , id : nil ) picker_options = { id : id || sanitize_to_id ( name ) , class : "picker-single" , name : name } prompt_params = yield ( nil ) selected_scopes = value ? Decidim :: Scope . where ( id : value ) : [ ] scopes = selected_scopes . map { | scope | [ scope , yield ( scope ) ] } template = "" template += render ( "decidim/scopes/scopes_picker_input" , picker_options : picker_options , prompt_params : prompt_params , scopes : scopes , checkboxes_on_top : true ) template . html_safe end | A custom helper to include a scope picker field without requiring a form object |
541 | def translated_field_tag ( type , object_name , name , value = { } , options = { } ) locales = available_locales field_label = label_tag ( name , options [ :label ] ) if locales . count == 1 field_name = "#{name}_#{locales.first.to_s.gsub("-", "__")}" field_input = send ( type , "#{object_name}[#{field_name}]" , value [ locales . first . to_s ] ) return safe_join [ field_label , field_input ] end tabs_id = options [ :tabs_id ] || "#{object_name}-#{name}-tabs" . underscore enabled_tabs = options [ :enable_tabs ] . nil? ? true : options [ :enable_tabs ] tabs_panels_data = enabled_tabs ? { tabs : true } : { } label_tabs = content_tag ( :div , class : "label--tabs" ) do tabs_panels = "" . html_safe if options [ :label ] != false tabs_panels = content_tag ( :ul , class : "tabs tabs--lang" , id : tabs_id , data : tabs_panels_data ) do locales . each_with_index . inject ( "" . html_safe ) do | string , ( locale , index ) | string + content_tag ( :li , class : tab_element_class_for ( "title" , index ) ) do title = I18n . with_locale ( locale ) { I18n . t ( "name" , scope : "locale" ) } element_class = nil element_class = "is-tab-error" if form_field_has_error? ( options [ :object ] , name_with_locale ( name , locale ) ) tab_content_id = "#{tabs_id}-#{name}-panel-#{index}" content_tag ( :a , title , href : "##{tab_content_id}" , class : element_class ) end end end end safe_join [ field_label , tabs_panels ] end tabs_content = content_tag ( :div , class : "tabs-content" , data : { tabs_content : tabs_id } ) do locales . each_with_index . inject ( "" . html_safe ) do | string , ( locale , index ) | tab_content_id = "#{tabs_id}-#{name}-panel-#{index}" string + content_tag ( :div , class : tab_element_class_for ( "panel" , index ) , id : tab_content_id ) do send ( type , "#{object_name}[#{name_with_locale(name, locale)}]" , value [ locale . to_s ] , options . merge ( id : "#{tabs_id}_#{name}_#{locale}" , label : false ) ) end end end safe_join [ label_tabs , tabs_content ] end | A custom helper to include a translated field without requiring a form object . |
542 | def decidim_form_slug_url ( prepend_path = "" , value = "" ) prepend_slug_path = if prepend_path . present? "/#{prepend_path}/" else "/" end content_tag ( :span , class : "slug-url" ) do [ request . protocol , request . host_with_port , prepend_slug_path ] . join ( "" ) . html_safe + content_tag ( :span , value , class : "slug-url-value" ) end end | Helper method to show how slugs will look like . Intended to be used in forms together with some JavaScript code . More precisely this will most probably show in help texts in forms . The space slug is surrounded with a span so the slug can be updated via JavaScript with the input value . |
543 | def render_resource_last_editor ( resource ) render partial : "decidim/shared/version_author" , locals : { author : Decidim . traceability . last_editor ( resource ) } end | Renders the avatar and author name of the author of the last version of the given resource . |
544 | def render_resource_editor ( version ) render partial : "decidim/shared/version_author" , locals : { author : Decidim . traceability . version_editor ( version ) } end | Renders the avatar and author name of the author of the given version . |
545 | def diff_renderer @diff_renderer ||= if current_version . item_type . include? "Decidim::Proposals" Decidim :: Proposals :: DiffRenderer . new ( current_version ) elsif current_version . item_type . include? "Decidim::Accountability" Decidim :: Accountability :: DiffRenderer . new ( current_version ) end end | Caches a DiffRenderer instance for the current_version . |
546 | def render_diff_value ( value , type , action , options = { } ) return "" . html_safe if value . blank? value_to_render = case type when :date l value , format : :long when :percentage number_to_percentage value , precision : 2 else value end content_tag ( :div , class : "card--list__item #{action}" ) do content_tag ( :div , class : "card--list__text" ) do content_tag ( :div , { class : "diff__value" } . merge ( options ) ) do value_to_render end end end end | Renders the given value in a user - friendly way based on the value class . |
547 | def title resource_title = resource . try ( :resource_title ) || resource . try ( :title ) return if resource_title . blank? if resource_title . is_a? ( String ) resource_title elsif resource_title . is_a? ( Hash ) translated_attribute ( resource_title ) end end | The title to show at the card . |
548 | def description resource_description = resource . try ( :resource_description ) || resource . try ( :description ) return if resource_description . blank? resource_description = if resource_description . is_a? ( String ) resource_description elsif resource_description . is_a? ( Hash ) translated_attribute ( resource_description ) end truncate ( strip_tags ( resource_description ) , length : 300 ) end | The description to show at the card . |
549 | def cta_button button_text = translated_attribute ( current_organization . cta_button_text ) . presence || t ( "decidim.pages.home.hero.participate" ) link_to button_text , cta_button_path , class : "hero-cta button expanded large button--sc" end | Renders the Call To Action button . Link and text can be configured per organization . |
550 | def cta_button_path if current_organization . cta_button_path . present? current_organization . cta_button_path elsif Decidim :: ParticipatoryProcess . where ( organization : current_organization ) . published . any? decidim_participatory_processes . participatory_processes_path elsif current_user decidim . account_path elsif current_organization . sign_up_enabled? decidim . new_user_registration_path else decidim . new_user_session_path end end | Finds the CTA button path to reuse it in other places . |
551 | def file_path directory_name = Rails . root . join ( Decidim :: DataPortabilityUploader . new . store_dir ) FileUtils . mkdir_p ( directory_name ) unless File . exist? ( directory_name ) directory_name + file_name end | Returns a String with the absolute file_path to be read or generate . |
552 | def filter_form_for ( filter , url = url_for ) content_tag :div , class : "filters" do form_for filter , namespace : filter_form_namespace , builder : FilterFormBuilder , url : url , as : :filter , method : :get , remote : true , html : { id : nil } do | form | yield form end end end | This method wraps everything in a div with class filters and calls the form_for helper with a custom builder |
553 | def image? ( new_file ) content_type = model . content_type || new_file . content_type content_type . to_s . start_with? "image" end | Checks if the file is an image based on the content type . We need this so we only create different versions of the file when it s an image . |
554 | def set_content_type_and_size_in_model model . content_type = file . content_type if file . content_type model . file_size = file . size end | Copies the content type and file size to the model where this is mounted . |
555 | def collection_radio_buttons ( method , collection , value_method , label_method , options = { } , html_options = { } ) fieldset_wrapper options [ :legend_title ] do super ( method , collection , value_method , label_method , options , html_options ) do | builder | if block_given? yield builder else builder . label { builder . radio_button + builder . text } end end end end | Wrap the radio buttons collection in a custom fieldset . It also renders the inputs inside its labels . |
556 | def collection_check_boxes ( method , collection , value_method , label_method , options = { } , html_options = { } ) fieldset_wrapper options [ :legend_title ] do super ( method , collection , value_method , label_method , options , html_options ) do | builder | if block_given? yield builder else builder . label { builder . check_box + builder . text } end end end end | Wrap the check_boxes collection in a custom fieldset . It also renders the inputs inside its labels . |
557 | def execute ( * ) file , line , = caller . first . split ( ":" ) colors = SSHKit :: Color . new ( $stderr ) $stderr . puts colors . colorize ( "Warning: `execute' should be wrapped in an `on' scope in #{file}:#{line}." , :red ) $stderr . puts $stderr . puts " task :example do" $stderr . puts colors . colorize ( " on roles(:app) do" , :yellow ) $stderr . puts " execute 'whoami'" $stderr . puts colors . colorize ( " end" , :yellow ) $stderr . puts " end" $stderr . puts raise NoMethodError , "undefined method `execute' for main:Object" end | Catch common beginner mistake and give a helpful error message on stderr |
558 | def warm_all threads = [ ] all_functions . each do | function_name | next if function_name . include? ( 'jets-public_controller' ) next if function_name . include? ( 'jets-rack_controller' ) threads << Thread . new do warm ( function_name ) end end threads . each { | t | t . join } warm_public_controller_more warm_rack_controller_more all_functions end | Loop through all methods for each class and makes special prewarm call to each method . |
559 | def iot_event ( props = { } ) if props . is_a? ( String ) props = { sql : props } topic_props = { topic_rule_payload : props } elsif props . key? ( :topic_rule_payload ) topic_props = props else topic_props = { topic_rule_payload : props } end declare_iot_topic ( topic_props ) end | The user must at least pass in an SQL statement |
560 | def lookup_class_properties ( klass ) all_classes = [ ] while klass != Object all_classes << klass klass = klass . superclass end class_properties = { } all_classes . reverse . each do | k | class_properties . merge! ( k . class_properties ) end class_properties end | Accounts for inherited class_properties |
561 | def finalize_properties! ( props ) handler = full_handler ( props ) runtime = get_runtime ( props ) managed = { handler : handler , runtime : runtime , description : description , } managed [ :function_name ] = function_name if function_name layers = get_layers ( runtime ) managed [ :layers ] = layers if layers props . merge! ( managed ) end | Properties managed by Jets with merged with finality . |
562 | def standardize ( definition ) case definition when String definition = "#{definition}:*" unless definition . include? ( ':' ) @policy [ :statement ] << { action : [ definition ] , effect : "Allow" , resource : "*" , } when Hash definition = definition . stringify_keys if definition . key? ( "Version" ) @policy = definition else @policy [ :statement ] << definition end end end | only process policy_document once |
563 | def process status , headers , body = Jets . application . call ( env ) convert_to_api_gateway ( status , headers , body ) end | 1 . Convert API Gateway event event to Rack env 2 . Process using full Rack middleware stack 3 . Convert back to API gateway response structure payload |
564 | def check_collision! paths = self . routes . map ( & :path ) collision = Jets :: Resource :: ApiGateway :: RestApi :: Routes :: Collision . new collide = collision . collision? ( paths ) raise collision . exception if collide end | Validate routes that deployable |
565 | def resources ( name ) get "#{name}" , to : "#{name}#index" get "#{name}/new" , to : "#{name}#new" unless api_mode? get "#{name}/:id" , to : "#{name}#show" post "#{name}" , to : "#{name}#create" get "#{name}/:id/edit" , to : "#{name}#edit" unless api_mode? put "#{name}/:id" , to : "#{name}#update" post "#{name}/:id" , to : "#{name}#update" patch "#{name}/:id" , to : "#{name}#update" delete "#{name}/:id" , to : "#{name}#delete" end | resources macro expands to all the routes |
566 | def all_paths results = [ ] paths = routes . map ( & :path ) paths . each do | p | sub_paths = [ ] parts = p . split ( '/' ) until parts . empty? parts . pop sub_path = parts . join ( '/' ) sub_paths << sub_path unless sub_path == '' end results += sub_paths end @all_paths = ( results + paths ) . sort . uniq end | Useful for creating API Gateway Resources |
567 | def ordered_routes length = Proc . new { | r | r . path . length * - 1 } capture_routes = routes . select { | r | r . path . include? ( ':' ) } . sort_by ( & length ) wildcard_routes = routes . select { | r | r . path . include? ( '*' ) } . sort_by ( & length ) simple_routes = ( routes - capture_routes - wildcard_routes ) . sort_by ( & length ) simple_routes + capture_routes + wildcard_routes end | Useful for RouterMatcher |
568 | def routes_table routes = Jets :: Router . routes return "Your routes table is empty." if routes . empty? text = "Verb | Path | Controller#action\n" text << "--- | --- | ---\n" routes . each do | route | text << "#{route.method} | #{route.path} | #{route.to}\n" end html = Kramdown :: Document . new ( text ) . to_html puts html html end | Show pretty route table for user to help with debugging in non - production mode |
569 | def cors_headers rack = Jets :: Controller :: Middleware :: Cors . new ( Jets . application ) rack . cors_headers ( true ) end | Always the pre - flight headers in this case |
570 | def serve Bundler . with_clean_env do args = '' if @options [ :host ] args << " --host #{@options[:host]}" else args << " --host 127.0.0.1" end command = "cd #{rack_project} && bin/rackup#{args}" puts "=> #{command}" . color ( :green ) system ( command ) end end | Runs in the child process |
571 | def wait_for_socket return unless Jets . rack? retries = 0 max_retries = 30 delay = 0.5 if ENV [ 'C9_USER' ] max_retries = 3 delay = 3 end begin server = TCPSocket . new ( 'localhost' , 9292 ) server . close rescue Errno :: ECONNREFUSED puts "Unable to connect to localhost:9292. Delay for #{delay} and will try to connect again." if ENV [ 'JETS_DEBUG' ] sleep ( delay ) retries += 1 if retries < max_retries retry else puts "Giving up on trying to connect to localhost:9292" return false end end puts "Connected to localhost:9292 successfully" true end | blocks until rack server is up |
572 | def add ( severity , message = nil , progname = nil ) if message . nil? if block_given? message = yield else message = progname progname = @progname end end IO . buffer << message super end | Only need to override the add method as the other calls all lead to it . |
573 | def long_description text = @command . long_description return "" if text . nil? lines = text . split ( "\n" ) lines . map do | line | line . sub ( / \b / , ' ' ) end . join ( "\n" ) end | Use command s long description as main description |
574 | def options exclude = %w[ docs spec vendor core.rb .js templates commands internal support Dockerfile Dockerfile.base Gemfile Gemfile.lock Guardfile LICENSE Procfile Rakefile bin ] exclude = exclude . map { | word | [ '-x' , word ] } . flatten [ "-m" , "README.md" , "--markup" , "tomdoc" ] + exclude end | Use for both jets . gemspec and rake rdoc task |
575 | def use_webpacker ( middleware ) return unless Jets . webpacker? return if File . exist? ( "#{Jets.root}/config/disable-webpacker-middleware.txt" ) require "jets/controller/middleware/webpacker_setup" middleware . use Webpacker :: DevServerProxy end | Written as method to easily not include webpacker for case when either webpacker not installed at all or disabled upon jets deploy . |
576 | def account return '123456789' if test? ENV [ 'AWS_REGION' ] ||= region begin sts . get_caller_identity . account rescue Aws :: Errors :: MissingCredentialsError puts "INFO: You're missing AWS credentials. Only local services are currently available" end end | aws sts get - caller - identity |
577 | def check_route_connected_functions return if Jets :: Router . all_routes_valid puts "Deploy fail: The jets application contain invalid routes." . color ( :red ) puts "Please double check the routes below map to valid controllers:" Jets :: Router . invalid_routes . each do | route | puts " /#{route.path} => #{route.controller_name}##{route.action_name}" end exit 1 end | Checks that all routes are validate and have corresponding lambda functions |
578 | def minimal_rollback_complete? stack = find_stack ( stack_name ) return false unless stack return false unless stack . stack_status == 'ROLLBACK_COMPLETE' resp = cfn . describe_stack_resources ( stack_name : stack_name ) resource_statuses = resp . stack_resources . map ( & :resource_status ) . uniq resource_statuses == [ 'DELETE_COMPLETE' ] end | Checks for a few things before deciding to delete the parent stack |
579 | def all_classes klass = @app_class . constantize all_classes = [ ] while klass != Object all_classes << klass klass = klass . superclass end all_classes . reverse end | Class heirachry in top to down order |
580 | def adjust_tasks ( klass ) class_name = @code_path . to_s . sub ( / \/ \/ / , '' ) . sub ( / \. / , '' ) class_name = class_name . classify klass . tasks . each do | task | task . class_name = class_name task . type = "function" end end | For anonymous classes method_added during task registration contains for the class name . We adjust it here . |
581 | def generate_content content = "" if @issues . any? content += "#{@prefix}\n\n" unless @options [ :simple_list ] || @prefix . blank? @issues . each do | issue | merge_string = get_string_for_issue ( issue ) content += "- " unless @body_only content += "#{merge_string}\n" end content += "\n" end content end | Returns the content of a section . |
582 | def get_string_for_issue ( issue ) encapsulated_title = encapsulate_string issue [ "title" ] title_with_number = "#{encapsulated_title} [\\##{issue['number']}](#{issue['html_url']})" title_with_number = "#{title_with_number}#{line_labels_for(issue)}" if @options [ :issue_line_labels ] . present? line = issue_line_with_user ( title_with_number , issue ) issue_line_with_body ( line , issue ) end | Parse issue and generate single line formatted issue line . |
583 | def encapsulate_string ( string ) string = string . gsub ( '\\' , '\\\\' ) ENCAPSULATED_CHARACTERS . each do | char | string = string . gsub ( char , "\\#{char}" ) end string end | Encapsulate characters to make Markdown look as expected . |
584 | def fetch_tags_dates ( tags ) print "Fetching tag dates...\r" if options [ :verbose ] i = 0 tags . each do | tag | get_time_of_tag ( tag ) i += 1 end puts "Fetching tags dates: #{i}/#{tags.count}" if options [ :verbose ] end | Async fetching of all tags dates |
585 | def detect_actual_closed_dates ( issues ) print "Fetching closed dates for issues...\r" if options [ :verbose ] i = 0 issues . each do | issue | find_closed_date_by_commit ( issue ) i += 1 end puts "Fetching closed dates for issues: #{i}/#{issues.count}" if options [ :verbose ] end | Find correct closed dates if issues was closed by commits |
586 | def add_first_occurring_tag_to_prs ( tags , prs ) total = prs . count prs_left = associate_tagged_prs ( tags , prs , total ) prs_left = associate_release_branch_prs ( prs_left , total ) prs_left = associate_rebase_comment_prs ( tags , prs_left , total ) if prs_left . any? @pull_requests -= prs_left Helper . log . info "Associating PRs with tags: #{total}/#{total}" end | Adds a key first_occurring_tag to each PR with a value of the oldest tag that a PR s merge commit occurs in in the git history . This should indicate the release of each PR by git s history regardless of dates and divergent branches . |
587 | def associate_tagged_prs ( tags , prs , total ) @fetcher . fetch_tag_shas_async ( tags ) i = 0 prs . reject do | pr | found = false if pr [ "events" ] && ( event = pr [ "events" ] . find { | e | e [ "event" ] == "merged" } ) if ( oldest_tag = tags . reverse . find { | tag | tag [ "shas_in_tag" ] . include? ( event [ "commit_id" ] ) } ) pr [ "first_occurring_tag" ] = oldest_tag [ "name" ] found = true i += 1 print ( "Associating PRs with tags: #{i}/#{total}\r" ) if @options [ :verbose ] end else no_events_pr = associate_rebase_comment_prs ( tags , [ pr ] , total ) raise StandardError , "No merge sha found for PR #{pr['number']} via the GitHub API" unless no_events_pr . empty? found = true i += 1 print ( "Associating PRs with tags: #{i}/#{total}\r" ) if @options [ :verbose ] end found end end | Associate merged PRs by the merge SHA contained in each tag . If the merge_commit_sha is not found in any tag s history skip association . |
588 | def set_date_from_event ( event , issue ) if event [ "commit_id" ] . nil? issue [ "actual_date" ] = issue [ "closed_at" ] else begin commit = @fetcher . fetch_commit ( event [ "commit_id" ] ) issue [ "actual_date" ] = commit [ "commit" ] [ "author" ] [ "date" ] rescue StandardError puts "Warning: Can't fetch commit #{event['commit_id']}. It is probably referenced from another repo." issue [ "actual_date" ] = issue [ "closed_at" ] end end end | Set closed date from this issue |
589 | def calculate_pages ( client , method , request_options ) check_github_response do client . send ( method , user_project , DEFAULT_REQUEST_OPTIONS . merge ( request_options ) ) end last_response = client . last_response if ( last_pg = last_response . rels [ :last ] ) querystring_as_hash ( last_pg . href ) [ "page" ] . to_i else 1 end end | Returns the number of pages for a API call |
590 | def github_fetch_tags tags = [ ] page_i = 0 count_pages = calculate_pages ( @client , "tags" , { } ) iterate_pages ( @client , "tags" ) do | new_tags | page_i += PER_PAGE_NUMBER print_in_same_line ( "Fetching tags... #{page_i}/#{count_pages * PER_PAGE_NUMBER}" ) tags . concat ( new_tags ) end print_empty_line if tags . count == 0 Helper . log . warn "Warning: Can't find any tags in repo. \Make sure, that you push tags to remote repo via 'git push --tags'" else Helper . log . info "Found #{tags.count} tags" end tags . map { | resource | stringify_keys_deep ( resource . to_hash ) } end | Fill input array with tags |
591 | def fetch_events_async ( issues ) i = 0 threads = [ ] issues . each_slice ( MAX_THREAD_NUMBER ) do | issues_slice | issues_slice . each do | issue | threads << Thread . new do issue [ "events" ] = [ ] iterate_pages ( @client , "issue_events" , issue [ "number" ] ) do | new_event | issue [ "events" ] . concat ( new_event ) end issue [ "events" ] = issue [ "events" ] . map { | event | stringify_keys_deep ( event . to_hash ) } print_in_same_line ( "Fetching events for issues and PR: #{i + 1}/#{issues.count}" ) i += 1 end end threads . each ( & :join ) threads = [ ] end print_empty_line Helper . log . info "Fetching events for issues and PR: #{i}" end | Fetch event for all issues and add them to events |
592 | def fetch_comments_async ( prs ) threads = [ ] prs . each_slice ( MAX_THREAD_NUMBER ) do | prs_slice | prs_slice . each do | pr | threads << Thread . new do pr [ "comments" ] = [ ] iterate_pages ( @client , "issue_comments" , pr [ "number" ] ) do | new_comment | pr [ "comments" ] . concat ( new_comment ) end pr [ "comments" ] = pr [ "comments" ] . map { | comment | stringify_keys_deep ( comment . to_hash ) } end end threads . each ( & :join ) threads = [ ] end nil end | Fetch comments for PRs and add them to comments |
593 | def fetch_date_of_tag ( tag ) commit_data = fetch_commit ( tag [ "commit" ] [ "sha" ] ) commit_data = stringify_keys_deep ( commit_data . to_hash ) commit_data [ "commit" ] [ "committer" ] [ "date" ] end | Fetch tag time from repo |
594 | def fetch_compare ( older , newer ) unless @compares [ "#{older}...#{newer}" ] compare_data = check_github_response { @client . compare ( user_project , older , newer || "HEAD" ) } raise StandardError , "Sha #{older} and sha #{newer} are not related; please file a github-changelog-generator issues and describe how to replicate this issue." if compare_data [ "status" ] == "diverged" @compares [ "#{older}...#{newer}" ] = stringify_keys_deep ( compare_data . to_hash ) end @compares [ "#{older}...#{newer}" ] end | Fetch and cache comparison between two github refs |
595 | def fetch_commit ( commit_id ) found = commits . find do | commit | commit [ "sha" ] == commit_id end if found stringify_keys_deep ( found . to_hash ) else check_github_response do commit = @client . commit ( user_project , commit_id ) commit = stringify_keys_deep ( commit . to_hash ) commit end end end | Fetch commit for specified event |
596 | def fetch_tag_shas_async ( tags ) i = 0 threads = [ ] print_in_same_line ( "Fetching SHAs for tags: #{i}/#{tags.count}\r" ) if @options [ :verbose ] tags . each_slice ( MAX_THREAD_NUMBER ) do | tags_slice | tags_slice . each do | tag | threads << Thread . new do commits_in_tag = fetch_compare ( oldest_commit [ "sha" ] , tag [ "name" ] ) tag [ "shas_in_tag" ] = commits_in_tag [ "commits" ] . collect { | commit | commit [ "sha" ] } print_in_same_line ( "Fetching SHAs for tags: #{i + 1}/#{tags.count}" ) if @options [ :verbose ] i += 1 end end threads . each ( & :join ) threads = [ ] end print_empty_line Helper . log . info "Fetching SHAs for tags: #{i}" nil end | Fetch all SHAs occurring in or before a given tag and add them to shas_in_tag |
597 | def check_github_response Retriable . retriable ( retry_options ) do yield end rescue MovedPermanentlyError => e fail_with_message ( e , "The repository has moved, update your configuration" ) rescue Octokit :: Forbidden => e fail_with_message ( e , "Exceeded retry limit" ) rescue Octokit :: Unauthorized => e fail_with_message ( e , "Error: wrong GitHub token" ) end | This is wrapper with rescue block |
598 | def fetch_and_filter_tags since_tag due_tag all_tags = @fetcher . get_all_tags fetch_tags_dates ( all_tags ) all_sorted_tags = sort_tags_by_date ( all_tags ) @sorted_tags = filter_excluded_tags ( all_sorted_tags ) @filtered_tags = get_filtered_tags ( @sorted_tags ) section_tags = get_filtered_tags ( all_sorted_tags ) @tag_section_mapping = build_tag_section_mapping ( section_tags , @filtered_tags ) @filtered_tags end | fetch filter tags fetch dates and sort them in time order |
599 | def get_time_of_tag ( tag_name ) raise ChangelogGeneratorError , "tag_name is nil" if tag_name . nil? name_of_tag = tag_name . fetch ( "name" ) time_for_tag_name = @tag_times_hash [ name_of_tag ] return time_for_tag_name if time_for_tag_name @fetcher . fetch_date_of_tag ( tag_name ) . tap do | time_string | @tag_times_hash [ name_of_tag ] = time_string end end | Returns date for given GitHub Tag hash |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.