idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
8,100 | def main_arena return @main_arena . reload! if defined? @main_arena off = main_arena_offset return if off . nil? @main_arena = Arena . new ( off + base , size_t , dumper ) end | Get the + main_arena + of libc . |
8,101 | def info return @info if defined? @info key = HeapInfo :: Cache . key_libc_info ( name ) @info = HeapInfo :: Cache . read ( key ) @info ||= execute_libc_info . tap { | i | HeapInfo :: Cache . write ( key , i ) } end | Get libc s info . |
8,102 | def method_missing ( method_sym , * args , & block ) return nil . __send__ ( method_sym , * args , & block ) if nil . respond_to? ( method_sym ) self end | Hook all missing methods |
8,103 | def invalid_pointer ( ptr , size ) errmsg = "free(): invalid pointer\n" malloc_assert ( ptr <= ulong ( - size ) ) { errmsg + format ( 'ptr(0x%x) > -size(0x%x)' , ptr , ulong ( - size ) ) } malloc_assert ( ( ptr % ( size_t * 2 ) ) . zero? ) { errmsg + format ( 'ptr(0x%x) %% %d != 0' , ptr , size_t * 2 ) } end | Start of checkers |
8,104 | def flags mask = @size - size flag = [ ] flag << :non_main_arena unless ( mask & 4 ) . zero? flag << :mmapped unless ( mask & 2 ) . zero? flag << :prev_inuse unless ( mask & 1 ) . zero? flag end | The chunk flags record in low three bits of size |
8,105 | def offset ( addr , sym = nil ) return unless load? segment = @info . to_segment ( sym ) if segment . nil? sym , segment = @info . segments . select { | _ , seg | seg . base <= addr } . min_by { | _ , seg | addr - seg } end return $stdout . puts "Invalid address #{Helper.hex(addr)}" if segment . nil? $stdout . puts Hel... | Show the offset in pretty way between the segment . Very useful in pwn when leak some address see examples for more details . |
8,106 | def find ( pattern , from , length = :unlimited , rel : false ) return Nil . instance unless load? dumper . find ( pattern , from , length , rel ) end | Gdb - like command . |
8,107 | def find_all ( pattern , segment = :all ) return Nil . instance unless load? segments = segment == :all ? %i[ elf heap libc ld stack ] : Array ( segment ) result = findall_raw ( pattern , segments ) . reject { | ( _ , _ , ary ) | ary . empty? } target = pattern . is_a? ( Integer ) ? Helper . hex ( pattern ) : pattern .... | Find pattern in all segments with pretty output . |
8,108 | def to_s return 'Process not found' unless load? "Program: #{Helper.color(program.name)} PID: #{Helper.color(pid)}\n" + program . to_s + heap . to_s + stack . to_s + libc . to_s + ld . to_s + format ( "%-28s\tvalue: #{Helper.color(format('%#x', canary), sev: :sym)}" , Helper . color ( 'canary' , sev : :sym ) ) end | Show simple information of target process . |
8,109 | def canary return Nil . instance unless load? addr = @info . auxv [ :random ] Helper . unpack ( bits / 8 , @dumper . dump ( addr , bits / 8 ) ) & 0xffffffffffffff00 end | Get the value of stack guard . |
8,110 | def read @field_stream . read = @read field_count = FIELDS . length fields = @field_stream . each ( self . class . delimiter , field_count , PS4_START_REGEXP ) loop do break if ( hit = ( 1 .. field_count ) . map { fields . next } ) . empty? parse_hit! ( * hit ) end @read . close unless @read . closed? @files end | Read fields extracted from Bash s debugging output |
8,111 | def update_wd_stacks! ( pwd , oldpwd ) @pwd_stack [ 0 ] ||= pwd @oldpwd_stack [ 0 ] ||= oldpwd unless oldpwd . to_s . empty? return if pwd == @pwd_stack [ - 1 ] if pwd == @oldpwd_stack [ - 1 ] && oldpwd == @oldpwd_stack [ - 2 ] @pwd_stack . pop @oldpwd_stack . pop else @pwd_stack << pwd @oldpwd_stack << oldpwd end end | Updates the stacks that track the history of values for + PWD + and + OLDPWD + |
8,112 | def shellscript? ( filename ) return false unless File . exist? ( filename ) && File . readable? ( filename ) && File . file? ( File . realpath ( filename ) ) shellscript_shebang? ( filename ) || ( shellscript_extension? ( filename ) && shellscript_syntax? ( filename ) ) end | Create an object that can be used for inferring whether a file is or is not a shell script . |
8,113 | def each ( delimiter , field_count , start_match ) return enum_for ( __method__ , delimiter , field_count , start_match ) unless block_given? chunked = each_field ( delimiter ) . chunk ( & chunk_matches ( start_match ) ) yield_fields = lambda do | ( _ , chunk ) | chunk . each { | e | yield e } ( field_count - chunk . s... | Yields fields extracted from a input stream |
8,114 | def build_package filename = config . tarball_filename ( config . toml [ :package ] [ :version ] ) relative_library_path = config . ruby_extension_path . sub ( "#{config.ruby_toplevel_dir}/" , '' ) prepare_built_library Zlib :: GzipWriter . open ( filename ) do | tgz | Dir . chdir ( config . ruby_toplevel_dir ) do Arch... | Builds a tarball of the Rust - compiled shared library . |
8,115 | def debug ( msg ) return unless config . debug_filename @debug ||= File . open ( config . debug_filename , 'w' ) @debug . write ( "#{msg}\n" ) @debug . flush end | Logs a debug message to the specified config . debug_filename if set . |
8,116 | def download_binary_from_custom_uri return false unless config . binary_uri_format version = config . crate_version uri ||= format ( config . binary_uri_format , filename : config . tarball_filename ( version ) , version : version ) return false unless ( tgz = download_versioned_binary ( uri , version ) ) debug "Unpack... | Downloads a Rust binary using a custom URI format given the target OS and architecture . |
8,117 | def on_error yield rescue Github :: Error :: NotFound => e terminal . newline ui . error 'Resource Not Found' terminal . newline exit 15 rescue GithubCLI :: GithubCLIError => e GithubCLI . ui . error e . message GithubCLI . ui . debug e exit e . status_code rescue Interrupt => e GithubCLI . ui . error "\nQuitting..." G... | Defines behaviour on error to emit consistent type . |
8,118 | def convert_value ( value ) case value when true then "true" when false then "false" when Hash then convert_value ( value . values ) when Array then value . map ( & :to_s ) else value . to_s end end | Attempts to convert value object to string |
8,119 | def man_dir ( path = nil ) if @man_dir . nil? || path man_path = path || File . expand_path ( '../man' , __FILE__ ) if File . directory? ( man_path ) @man_dir = man_path else fail "Manuals directory `#{man_path}` does not exist" end end @man_dir end | Full path to manual directory |
8,120 | def manpage? ( name , section = nil ) return false if name . nil? manpages ( name , section ) . any? end | Check if manual exists for a command |
8,121 | def read ( name , section = nil ) return if name . nil? paths = manpages ( name ) return if paths . empty? if paths . size == 1 manpath = paths [ 0 ] elsif paths . size > 1 prompt = TTY :: Prompt . new manpath = prompt . select ( "Choose manual to view?" , paths ) end if manpath run ( manpath ) else abort ( "No manuals... | Read manual page |
8,122 | def page return if not $stdout . tty? read_io , write_io = IO . pipe if Kernel . fork $stdin . reopen ( read_io ) read_io . close write_io . close ENV [ 'LESS' ] = 'FSRX' Kernel . select [ $stdin ] pager = Pager . pager_command Kernel . exec pager rescue Kernel . exec "/bin/sh" , "-c" , pager else $stdout . reopen ( wr... | Pages output using configured pager . |
8,123 | def process_action ( * args ) super rescue Exception => exception raise if RocketPants . pass_through_errors? logger . error "Exception occured: #{exception.class.name} - #{exception.message}" logger . error "Exception backtrace:" exception . backtrace [ 0 , 10 ] . each do | backtrace_line | logger . error "=> #{backtr... | Overrides the processing internals to rescue any exceptions and handle them with the registered exception rescue handler . |
8,124 | def error! ( name , * args ) context = args . extract_options! klass = Errors [ name ] || Error exception = klass . new ( * args ) . tap { | e | e . context = context } raise exception end | Dynamically looks up and then throws the error given by a symbolic name . Optionally takes a string message argument and a hash of context . |
8,125 | def lookup_error_metadata ( exception ) context = lookup_error_context exception context . fetch ( :metadata , { } ) . merge lookup_error_extras ( exception ) end | Returns extra error details for a given object making it useable for hooking in external exceptions . |
8,126 | def render_error ( exception ) logger . debug "Exception raised: #{exception.class.name}: #{exception.message}" if logger normalised_class = exception . class . ancestors . detect do | klass | klass < StandardError and error_mapping . has_key? ( klass ) end if normalised_class mapped = error_mapping [ normalised_class ... | Renders an exception as JSON using a nicer version of the error name and error message following the typically error standard as laid out in the JSON api design . |
8,127 | def transform_response ( response , options = { } ) inner = response . delete ( "response" ) objects = unpack inner , options if response . has_key? ( "pagination" ) paginated_response objects , response else objects end end | Give a response hash from the api will transform it into the correct data type . |
8,128 | def paginated_response ( objects , container ) pagination = container . delete ( "pagination" ) WillPaginate :: Collection . create ( pagination [ "current" ] , pagination [ "per_page" ] ) do | collection | collection . replace objects collection . total_entries = pagination [ "count" ] end end | Returns an API response wrapped in a will_paginate collection using the pagination key in the response container to set up the current number of total entries and page details . |
8,129 | def unpack ( object , options = { } ) transformer = options [ :transformer ] || options [ :as ] transformer ? transformer . call ( object ) : object end | Finds and uses the transformer for a given incoming object to unpack it into a useful data type . |
8,130 | def links ( links = { } ) links . each_pair do | rel , uri | link rel , uri if uri end end | Lets you add a series of links for the current resource . |
8,131 | def render_json ( json , options = { } ) self . status = options [ :status ] if options [ :status ] self . content_type = options [ :content_type ] if options [ :content_type ] options = options . slice ( * RENDERING_OPTIONS ) json = encode_to_json ( json ) unless json . respond_to? ( :to_str ) self . status ||= :ok se... | Given a json object or encoded json will encode it and set it to be the output of the given page . |
8,132 | def exposes ( object , options = { } ) if Respondable . paginated? ( object ) paginated object , options elsif Respondable . collection? ( object ) collection object , options else if Respondable . invalid? ( object ) error! :invalid_resource , object . errors else resource object , options end end end | Exposes an object to the response - Essentiall it tells the controller that this is what we need to render . |
8,133 | def metadata_for ( object , options , type , singular ) { } . tap do | metadata | metadata [ :count ] = object . length unless singular metadata [ :pagination ] = Respondable . extract_pagination ( object ) if type == :paginated metadata . merge! options [ :metadata ] if options [ :metadata ] end end | Extracts the metadata for the current response merging in options etc . Implements a simple hook to allow adding extra metadata to your api . |
8,134 | def create_config_file ( access_token , ssh_key_path , ssh_user , ssh_port , region , image , size , ssh_key , private_networking , backups_enabled , ip6 , timeout ) ssh_key_path = File . join ( '~' , DEFAULT_SSH_KEY_PATH ) if ssh_key_path . empty? ssh_user = 'root' if ssh_user . empty? ssh_port = DEFAULT_SSH_PORT if s... | Writes a config file |
8,135 | def handle_error ( error ) case error when Savon :: SOAPFault return UnknownApiError . new ( error . message ) when Savon :: HTTPError if error . to_hash [ :code ] == 401 return AccountError . new ( "Unauthorized: invalid credentials" ) end return UnknownApiError . new ( error . message ) when Excon :: Errors :: Error ... | There s a potential bug in the creditsafe API where they actually return an HTTP 401 if you re unauthorized hence the sad special case below |
8,136 | def method_missing ( method_id , * args ) if [ :get , :post , :put , :delete ] . include? ( method_id ) path , options = * args options ||= { } options [ :query ] = ( default_params . merge ( options [ :query ] || { } ) ) options [ :headers ] = ( self . class . default_options [ :headers ] . merge ( options [ :headers ... | get post put and delete methods |
8,137 | def all ( page = 1 , limit = 100 , latest = true ) opts = connection . version == 2 ? { :unseen => latest } : { :latest => latest } connection . get ( resource_uri , { :query => { :limit => limit , :page => page } . merge ( opts ) } ) end | Pull every judgment |
8,138 | def solr_names_and_values ( field_name , field_value , index_types ) return { } if field_value . nil? index_types = Array ( index_types ) index_types . uniq! index_types . dup . each do | index_type | if index_type . to_s =~ / / index_types . delete index_type index_types . delete $1 . to_sym end end results = { } fiel... | Given a field name - value pair a data type and an array of index types returns a hash of mapped names and values . The values in the hash are _arrays_ and may contain multiple values . |
8,139 | def mongodb_connection ( options = { } , & block ) return @mongodb_conncetion if @mongodb_connection and ! block_given? options . stringify_keys! options [ 'adapter' ] ||= 'mongodb' @mongodb_connection = no_sql_connection ( options , & block ) end | self Returns a no_sql_connection which is bound to a mongodb adapter or builds a new no_sql_connection if block is given |
8,140 | def show return unless @out arguments = @format_arguments . map { | method | method = sprintf ( "fmt_%s" , method ) send ( method ) } line = sprintf ( @format , * arguments ) width = get_width if line . length == width - 1 @out . print ( line + eol ) @out . flush elsif line . length >= width @terminal_width = [ @termin... | Draws the bar |
8,141 | def call ( env ) return render ( 500 ) do | xml | xml . h2 ( "#{@key} env is not initialized" ) end unless env [ @key ] request = :: Rack :: Request . new ( env ) if action = dispatch_action ( request ) send ( action , request ) else @app . call ( env ) end end | Initialize RackSessionAccess middleware |
8,142 | def show ( request ) request . env [ @key ] . delete ( :rack_session_access_force_load_session ) session_hash = request . env [ @key ] . to_hash case File . extname ( request . path ) when ".raw" render do | xml | xml . h2 "Raw rack session data" xml . pre RackSessionAccess . encode ( session_hash ) end else render do ... | List session data |
8,143 | def edit ( request ) render do | xml | xml . h2 "Update rack session" xml . p "Put marshalized and encoded with base64 ruby hash into the form" xml . form ( { :action => action_path ( :update ) , :method => 'post' , :enctype => 'application/x-www-form-urlencoded' } ) do | form | form . input ( :type => 'hidden' , :name... | Render form for submit new session data |
8,144 | def update ( request ) begin data = request . params [ 'data' ] hash = RackSessionAccess . decode ( data ) hash . each { | k , v | request . env [ @key ] [ k ] = v } rescue => e return render ( 400 ) do | xml | xml . h2 ( "Bad data #{data.inspect}: #{e.message} " ) end end redirect_to action_path ( :show ) end | Update session data |
8,145 | def dispatch_action ( request ) method = request_method ( request ) path = request . path . sub ( / \. \w / , '' ) route = @routing . detect { | r | r [ 0 ] == method && r [ 1 ] == path } route [ 2 ] if route end | Dispatch action from request |
8,146 | def request_method ( request ) return request . request_method if request . request_method != 'POST' return request . params [ '_method' ] . upcase if request . params [ '_method' ] request . request_method end | Return HTTP method detect emulated method with _method param |
8,147 | def adjusted_entropy ( entropy_threshhold : 0 ) revpassword = base_password . reverse min_entropy = [ EntropyCalculator . calculate ( base_password ) , EntropyCalculator . calculate ( revpassword ) ] . min QWERTY_STRINGS . each do | qwertystr | qpassword = mask_qwerty_strings ( base_password , qwertystr ) qrevpassword ... | Returns the minimum entropy for the password s qwerty locality adjustments . If a threshhold is specified we will bail early to avoid unnecessary processing . |
8,148 | def adjusted_entropy ( min_word_length : 4 , extra_dictionary_words : [ ] , entropy_threshhold : - 1 ) dictionary_words = Regexp . union ( ( extra_dictionary_words + COMMON_PASSWORDS ) . compact . reject { | i | i . length < min_word_length } ) min_entropy = EntropyCalculator . calculate ( base_password ) PasswordVaria... | Returns the minimum entropy for the passwords dictionary adjustments . If a threshhold is specified we will bail early to avoid unnecessary processing . Note that we only check for the first matching word up to the threshhold if set . Subsequent matching words are not deductd . |
8,149 | def memoize ( * methods ) options = methods . last . kind_of? ( Hash ) ? methods . pop : { } method_freezer = Freezer . parse ( options ) || freezer methods . each { | method | memoize_method ( method , method_freezer ) } self end | Memoize a list of methods |
8,150 | def memoize_method ( method_name , freezer ) memoized_methods [ method_name ] = Memoizable :: MethodBuilder . new ( self , method_name , freezer ) . call end | Memoize the named method |
8,151 | def timeline_min @js = "" @css = Kompress :: CSS . new ( File . open ( "#{TimelineSetter::ROOT}/public/stylesheets/timeline-setter.css" ) . read ) . css libs = Dir . glob ( "#{TimelineSetter::ROOT}/public/javascripts/vendor/**" ) . select { | q | q =~ / / } libs . each { | lib | @js << File . open ( lib , 'r' ) . read ... | Create a minified one - page version of a timeline by minifying CSS and JS and embedding all assets into our ERB template . |
8,152 | def parse_db ( stream ) case stream . gets . to_i when DB_FORMAT @meta = Oj . load ( stream . gets ) @tables = Oj . load ( stream . gets ) return true when 3 .. 4 add_paths ( Oj . load ( stream . gets ) ) return false when 0 .. 2 len = stream . gets . to_i add_paths ( Marshal . load ( stream . read ( len ) ) ) return f... | returns true iff the database is in the most recent format |
8,153 | def prepare ( vector ) vertex = vector . normalize . clone vertex . index = @vertices . push ( vertex ) . length - 1 u = azimuth ( vector ) / 2.0 / Math :: PI + 0.5 v = inclination ( vector ) / Math :: PI + 0.5 vertex . uv = Vector2 . new ( u , 1.0 - v ) vertex end | Project vector onto sphere s surface |
8,154 | def make ( v1 , v2 , v3 ) face = Face3 . new ( v1 . index , v2 . index , v3 . index , [ v1 . clone , v2 . clone , v3 . clone ] ) @faces << face @centroid . copy ( v1 ) . add ( v2 ) . add ( v3 ) . divide_scalar ( 3 ) azi = azimuth ( @centroid ) @face_vertex_uvs [ 0 ] << [ correct_uv ( v1 . uv , v1 , azi ) , correct_uv (... | Approximate a curved face with recursively sub - divided triangles . |
8,155 | def subdivide ( face , detail ) cols = 2.0 ** detail a = prepare ( @vertices [ face . a ] ) b = prepare ( @vertices [ face . b ] ) c = prepare ( @vertices [ face . c ] ) v = [ ] for i in 0 .. cols do v [ i ] = [ ] aj = prepare ( a . clone . lerp ( c , i . to_f / cols . to_f ) ) bj = prepare ( b . clone . lerp ( c , i .... | Analytically subdivide a face to the required detail level . |
8,156 | def inclination ( vector ) Math . atan2 ( - vector . y , Math . sqrt ( vector . x * vector . x + vector . z * vector . z ) ) end | Angle above the XZ plane . |
8,157 | def correct_uv ( uv , vector , azimuth ) return Vector2 . new ( uv . x - 1.0 , uv . y ) if azimuth < 0 return Vector2 . new ( azimuth / 2.0 / Math :: PI + 0.5 , uv . y ) if vector . x . zero? && vector . z . zero? uv . clone end | Texture fixing helper . Spheres have some odd behaviours . |
8,158 | def filter_fallback ( filter ) if filter == NearestFilter || filter == NearestMipMapNearestFilter || f == NearestMipMapLinearFilter GL_NEAREST end GL_LINEAR end | Fallback filters for non - power - of - 2 textures |
8,159 | def update_virtual_light ( light , cascade ) virtual_light = light . shadow_cascade_array [ cascade ] virtual_light . position . copy ( light . position ) virtual_light . target . position . copy ( light . target . position ) virtual_light . look_at ( virtual_light . target ) virtual_light . shadow_camera_visible = lig... | synchronize virtual light with the original light |
8,160 | def update_shadow_camera ( camera , light ) shadow_camera = light . shadow_camera points_frustum = light . pointa_frustum points_world = light . points_world @min . set ( Float :: INFINITY , Float :: INFINITY , Float :: INFINITY ) @max . set ( - Float :: INFINITY , - Float :: INFINITY , - Float :: INFINITY ) 8 . times ... | fit shadow camera s ortho frustum to camera frustum |
8,161 | def get_object_material ( object ) if object . material . is_a? ( MeshFaceMaterial ) object . material . materials [ 0 ] else object . material end end | For the moment just ignore objects that have multiple materials with different animation methods Only the frst material will be taken into account for deciding which depth material to use for shadow maps |
8,162 | def show_title ( decorated ) raise :: ArgumentError unless decorated . is_a? ResourceDecorator [ to_model_label ( decorated . model_class ) , decorated . to_label ] . compact . join ': ' end | Title for show page of given resource |
8,163 | def user_portrait ( user = current_user ) email_method = security . email_method || :email email = ModuleUtils . try_to user , email_method if email . present? https = "http#{request.ssl? ? 's' : EMPTY_STRING}" email_md5 = :: Digest :: MD5 . hexdigest email . downcase image_source = "#{https}://www.gravatar.com/avatar/... | Image portrait for given user . - if email is present a gravatar image tag will be returned - otherwise an user icon will be returned |
8,164 | def logout_path ( user = current_user , app = main_app ) path = security . logout_path path ||= if defined? :: Devise scope = :: Devise :: Mapping . find_scope! user "destroy_#{scope}_session_path" end ModuleUtils . try_to app , path end | Logout path for given user |
8,165 | def logout_method ( user = current_user ) http_method = security . logout_method http_method || if defined? :: Devise scope = :: Devise :: Mapping . find_scope! user mapping = :: Devise . mappings [ scope ] mapping . sign_out_via end end | Logout method for given user |
8,166 | def find_controller_by ( params ) model_class = find_model_class_by params Map . controller_map ( model_class , params [ :resources_controller ] ) || default_controller ( params ) end | Find controller class |
8,167 | def find_model_class_by ( params ) model_class = Map . model_class_map params [ :resources ] return model_class unless MODEL_ACTIONS . include? params [ :action ] . to_sym raise ModelNotFound , params [ :resources ] unless model_class unless Map . mode_map [ model_class ] raise UnprocessableEntity , I18n . t ( 'errors.... | Find out the model class |
8,168 | def set_message_for ( exception , env ) session = env [ ActionDispatch :: Request :: Session :: ENV_SESSION_KEY ] || { } env [ ActionDispatch :: Flash :: KEY ] ||= ActionDispatch :: Flash :: FlashHash . from_session_value session [ 'flash' ] flash = env [ ActionDispatch :: Flash :: KEY ] flash [ :alert ] = exception . ... | Set flash error message |
8,169 | def validate_presence_of ( field_name , type ) type || raise ( :: ArgumentError , I18n . t ( 'errors.invalid.type_required' , field_name : field_name ) ) end | Validate presence of a type for given field name |
8,170 | def itooltip ( title , icon_suffix = 'info-circle' , html_options = { } ) html_options [ :title ] = title ( html_options [ :data ] ||= { } ) . merge! toggle : 'tooltip' , placement : 'top' fa_icon icon_suffix , html_options end | Build up tooltip |
8,171 | def imodal ( title , body , html_options = { } ) label ||= html_options . delete ( :label ) || html_options . delete ( :icon ) || fa_icon ( 'clone' ) content_tag :span , class : 'modaler' do concat link_to ( label , '#' , data : { target : '#imodal' , toggle : 'modal' } ) concat content_tag ( :span , title , class : 'm... | Build up modal |
8,172 | def error_messages ( field_name ) errors = Array object . errors [ field_name ] return if errors . blank? content_tag :ul , class : 'errors' do errors . each do | message | concat content_tag :li , content_tag ( :small , raw ( message ) ) end end end | Build up the HTML for displaying error messages |
8,173 | def label ( method , text = nil , options = { } , & block ) text = instance_exec ( & text ) if text . is_a? ( Proc ) super end | Extend label to accept proc type text argument |
8,174 | def select ( method , choices = nil , options = { } , html_options = { } , & block ) choices = instance_exec ( & choices ) if choices . is_a? ( Proc ) super end | Extend select to accept proc type choices argument |
8,175 | def method_missing ( method , * args , & block ) return super unless @template . respond_to? method self . class . delegate method , to : :@template @template . public_send method , * args , & block end | Delegate missing method to |
8,176 | def remote_url ( url , model_class , wildcard = 'QUERY' ) url || index_path ( model_class , url_params : { q : wildcard , per : pagination . page_size } ) end | To generate remote URL for auto select plugin . |
8,177 | def filter_link ( model_class , filter_name , filters : { } , url_params : { } ) is_all = filter_name == :all config = filters [ filter_name ] || { } label = is_all ? all_label : filter_label ( filter_name , filters ) url_params = if config [ :default ] then index_params . except ( :filter ) . merge ( url_params ) else... | Link for a given model class and filter name |
8,178 | def export_link ( model_class , url_params : { } ) url_params = index_params . except ( :page , :per ) . merge ( format : 'csv' ) . merge ( url_params ) index_link ( model_class , url_params : url_params ) { t 'links.export' , ext : 'CSV' } end | Export link for a given model_class . It accepts extra url params |
8,179 | def model_classes ( classes = Map . model_classes ) nested_hash = classes . each_with_object ( { } ) do | klass , hash | hash [ klass ] = Node . new ( klass ) end nested_hash . each do | klass , node | node . parent = parent = nested_hash [ klass . superclass ] parent . children << node if parent end nested_hash . valu... | Turn a list of classes into tree structure by inheritance . |
8,180 | def model_tree ( array , base_class = nil ) return EMPTY_STRING . html_safe if array . blank? options = { html_options : { class : 'dropdown-item' } } content_tag :ul , class : 'dropdown-menu' , 'aria-labelledby' : base_class do array . sort_by ( & :name ) . each do | node | content = index_link ( node . klass , option... | Turn the tree of classes into a nested ul list . |
8,181 | def init_provider ( context ) providers = Map . authorizer_provider_map model_class provider_class = providers [ self . class . provider_name ] provider_class ||= providers . values . find { | klass | klass . available? context } provider_class . new context end | Go through provider list and detect which provider is used . |
8,182 | def error_rendering ( exception , symbol ) Rails . logger . error exception @exception = exception @symbol = symbol @code = Rack :: Utils :: SYMBOL_TO_STATUS_CODE [ symbol ] . to_i respond_with @exception , status : @code , template : ERROR_PATH , prefixes : _prefixes end | Capture exceptions and display the error using error template . |
8,183 | def authorized? ( action , subject ) return false unless subject klass = subject . is_a? ( Class ) ? subject : subject . class authorizer_of ( klass ) . authorized? action , subject end | Check if user is allowed to perform action on given subject |
8,184 | def controller_to_get ( attribute_name , class_attribute_name = nil ) class_attribute_name ||= attribute_name return ModuleUtils . try_to self . class , class_attribute_name if is_a? :: ActionController :: Base ModuleUtils . try_to controller , attribute_name end | Fetch value for given attribute . |
8,185 | def find_template ( name , prefixes = [ ] , partial = false , keys = [ ] , options = { } ) prefixes = [ ] if partial && name . include? ( SLASH ) key = [ name , prefixes , partial , keys , options ] . map ( & :inspect ) . join ( SLASH ) cached_lookup [ key ] ||= super end | It overrides the oirgin method to call the origin find_template and cache the result during a request . |
8,186 | def authorize ( action , subject ) context . send ( :authorize , subject , normalize ( action ) ) && subject rescue :: Pundit :: NotAuthorizedError Rails . logger . info I18n . t ( 'errors.unauthorized' , user : user , action : action , subject : subject ) raise Forbidden end | Check user s permission for an action on given subject . |
8,187 | def authorized? ( action , subject ) policy = context . send :policy , subject ModuleUtils . try_to policy , normalize ( action ) end | Check and see if user is allowed to perform an action on given subject |
8,188 | def attributes_for ( action , subject ) policy = context . send :policy , subject value = ModuleUtils . try_to ( policy , "attributes_for_#{action}" ) || ModuleUtils . try_to ( policy , 'attributes_for' ) Rails . logger . warn I18n . t ( 'error.pundit.not_found.attributes_for' , subject : subject ) unless value value |... | Restrict user to assign certain values . |
8,189 | def permit_params ( action , subject ) policy = context . send :policy , subject ModuleUtils . try_to ( policy , "permitted_attributes_for_#{action}" ) || ModuleUtils . try_to ( policy , 'permitted_attributes' ) end | Restrict user for mass assignment . |
8,190 | def set_defaults_for ( action , options ) case action . try ( :to_sym ) when :create , :update then assign_create_and_update_defaults_with options when :destroy then assign_destroy_defaults_with options end options end | Set default options for create action |
8,191 | def authorize ( action , subject ) current_ability . authorize! action , subject rescue :: CanCan :: AccessDenied Rails . logger . info I18n . t ( 'errors.unauthorized' , user : user , action : action , subject : subject ) raise Forbidden end | Check user s permission for an action on given subject . This method will be used in controller . |
8,192 | def index_link ( model_class , url_params : { } , html_options : { } , & block ) return if unauthorized? :index , model_class html_options , block = LinkOptionsNormalizer . normalize ( html_options , block , block : -> { to_model_label model_class } ) path = index_path model_class , url_params : url_params link_to path... | Return link to index page by a given model class |
8,193 | def new_link ( model_class , html_options : { } , & block ) return if unauthorized? :new , model_class html_options , block = LinkOptionsNormalizer . normalize ( html_options , block , class : 'resource__create' , block : -> { t 'links.new' , model : to_model_label ( model_class ) } ) link_to new_path ( model_class ) ,... | Return link to create page by a given model class |
8,194 | def show_link ( resource , options : { } , html_options : { } , & block ) html_options , block = LinkOptionsNormalizer . normalize ( html_options , block , block : -> { decorate ( resource ) . to_label . to_s } ) default = options [ :readonly ] && block . call || nil return default if unauthorized? :show , extract ( re... | Return link to show page by a given model class If user s not authorized resource label will be returned |
8,195 | def edit_link ( resource , options : { } , html_options : { } , & block ) default = options [ :readonly ] && decorate ( resource ) . to_label || nil return default if unauthorized? :edit , extract ( resource ) html_options , block = LinkOptionsNormalizer . normalize ( html_options , block , class : 'resource__update' ,... | Return link to edit page by a given model class If user s not authorized resource label will be returned |
8,196 | def delete_link ( resource , options : { } , html_options : { } , & block ) return if unauthorized? :destroy , extract ( resource ) html_options , block = LinkOptionsNormalizer . normalize ( html_options , block , class : 'resource__destroy' , block : -> { t 'links.delete' } ) html_options [ :method ] ||= :delete html_... | Return link to delete action by a given model class |
8,197 | def index_path ( model_class , url_params : { } ) if url_params . is_a? ( :: ActionController :: Parameters ) && ! url_params . permitted? url_params = { } end url_for url_params . to_h . reverse_merge ( resources : to_resources_name ( model_class ) , action : :index ) end | Url for index page |
8,198 | def new_path ( model_class , url_params : { } ) url_for url_params . to_h . reverse_merge ( resources : to_resources_name ( model_class ) , action : :new ) end | Url for new resource form page |
8,199 | def edit_path ( resource , is_resource : false , url_params : { } ) decorated = decorate resource return unless is_resource || decorated . primary_key_value url_for ( url_params . to_h . reverse_merge ( resources : decorated . resources_name , action : :edit , id : decorated . primary_key_value ) . delete_if { | _ , v ... | Url for edit form page of given resource |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.