SHARE
TWEET

Rails name/hex lookup

a guest Jun 3rd, 2019 82 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class ColorsController < ApplicationController
  2.  
  3.   # Define colors catalog
  4.   @@colors = [
  5.     ['red',   'f00'],
  6.     ['green', '0f0'],
  7.     ['blue',  '00f']
  8.   ]
  9.  
  10.   # Define column names
  11.   @@indexes = {
  12.     'name' => 0,
  13.     'hex'  => 1
  14.   }
  15.  
  16.   # Index method
  17.   def index
  18.  
  19.     # Define result
  20.     @result = {}
  21.  
  22.     # We "try" some code ...
  23.     begin
  24.  
  25.       # Throw an error if parameter "what" or "which" is not provided
  26.       [:what, :which].each{ |param| raise "Parameter '#{param}'  not provided." if params[param].nil? }
  27.  
  28.       # Throw an error unless parameter "what" is found in indexes
  29.       raise 'Parameter "what"  not in catalog.' unless @@indexes.has_key? 'name'
  30.  
  31.       # Find the matching row in catalog via parameter "which"
  32.       # Note: Binary flip used here.  1-x  =>  1-1=0  or  1-0=1
  33.       row_found = @@colors.find{ |color| color[1 - @@indexes[params[:what]]] == params[:which] }
  34.  
  35.       # Throw an error if parameter "which" is not found in catalog
  36.       raise 'Parameter "which" not in catalog.' if row_found.nil?
  37.  
  38.       # Format output
  39.       @result[:message] = row_found[@@indexes[params[:what]]]
  40.       @result[:status]  = true
  41.  
  42.     # ... and catch an error if necessary (and format output)
  43.     rescue StandardError => error
  44.       @result[:message] = error
  45.       @result[:status]  = false
  46.  
  47.     end
  48.   end
  49. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top