working on it ...

Filters

Explore Public Snippets

Sort by

Found 39k snippets

    public by WFreelandEcon modified Jun 23, 2017  78  0  1  0

    Command line bar chart from JSON data (for GeekTool, et al)

    Command line bar chart from JSON data (for GeekTool, et al): barchart.rb
    #!/usr/bin/env ruby
    # encoding: utf-8
    # Brett Terpstra 2013, WTF license <http://www.wtfpl.net/txt/copying/>
    
    # Outputs a vertical bar chart from date-based JSON data
    # Requires the JSON rubygem: `[sudo] gem install json`
    require 'date'
    require 'open-uri'
    require 'rubygems'
    require 'json'
    
    # Data source URL (sample output at the end of script)
    data_url = "http://api.feedpress.it/feeds/..."
    # Parent container key for data object
    main_container = 'stats'
    # Repeated key for date/stats objects
    date_container = 'day'
    # keys for amounts to collect
    total_containers = ['greader','other','direct']
    
    # How many columns to output
    columns = 30
    # Total height will be determined by min and max valudes
    # scaled to max_rows
    max_rows = 15
    
    # If "test" is passed as an argument, load test data from end of script
    if ARGV[0] == "test" || !data_url || data_url.strip == ""
        input = DATA.read
        columns = 30
        max_rows = 18
        main_container = 'stats'
        date_container = 'day'
        total_containers = ['greader','other','direct']
    else
    # Otherwise, read data from the data url
        input = open(URI.parse(data_url)).read
    end
    
    json = JSON.parse(input)
    
    # Create two arrays, one for dates and one for totals
    dates = []
    totals = []
    # Step through data objects to populate both arrays sequentially
    json[main_container].each { |day|
        dates.push(Time.at(day[date_container]).to_datetime.strftime('%m/%d'))
        total = 0
        for item in total_containers
            total += day[item].to_i
        end
    
        totals.push(total)
    }
    
    # Find the highest and lowest values to determine bar heights
    max = totals.sort[-1]
    min = totals.sort[0]
    
    # Trim data arrays down to the maximum number of columns 
    # defined above
    dates = dates.reverse[0..columns]
    totals = totals.reverse[0..columns]
    
    # Determine number or rows to generate
    topline = max_rows
    div = max / topline
    bottomline = min/div
    
    # Output each row. If the total for the column is greater
    # than or equal to the scaled row counter, output a chunk 
    # of the bar
    topline.times do
        totals.each { |num|
            if num / div > topline
                print "◼ "
            else
                print "  "
            end
        }
        if topline + (max_rows/10).round == bottomline
            puts
            break
        else
            topline -= 1
            puts
        end
    end
    
    # Calculate average across all totals
    avg = totals.inject(0.0) { |sum, el| sum + el } / totals.size
    
    # Output a legend with today, peak and average
    puts "#{dates[0]} - #{dates[-1]} ⇒Today: #{totals[-1]} | Peak: #{max} | Average: #{avg.round}"
    puts
    
    # Sample data for testing
    __END__
    
    {
        "stats": [
            {
                "day": 1382914800,
                "greader": 10195,
                "other": 4409,
                "direct": 879,
                "newsletter": 0
            },
            {
                "day": 1382824800,
                "greader": 10174,
                "other": 4327,
                "direct": 843,
                "newsletter": 0
            },
            {
                "day": 1382738400,
                "greader": 10172,
                "other": 4173,
                "direct": 861,
                "newsletter": 0
            },
            {
                "day": 1382652000,
                "greader": 10182,
                "other": 4195,
                "direct": 853,
                "newsletter": 0
            },
            {
                "day": 1382565600,
                "greader": 10163,
                "other": 4207,
                "direct": 851,
                "newsletter": 0
            },
            {
                "day": 1382479200,
                "greader": 10135,
                "other": 4206,
                "direct": 839,
                "newsletter": 0
            },
            {
                "day": 1382392800,
                "greader": 8196,
                "other": 4437,
                "direct": 850,
                "newsletter": 0
            },
            {
                "day": 1382306400,
                "greader": 8181,
                "other": 4482,
                "direct": 819,
                "newsletter": 0
            },
            {
                "day": 1382220000,
                "greader": 9968,
                "other": 4413,
                "direct": 858,
                "newsletter": 0
            },
            {
                "day": 1382133600,
                "greader": 9972,
                "other": 4413,
                "direct": 859,
                "newsletter": 0
            },
            {
                "day": 1382047200,
                "greader": 10050,
                "other": 4375,
                "direct": 842,
                "newsletter": 0
            },
            {
                "day": 1381960800,
                "greader": 10056,
                "other": 4310,
                "direct": 821,
                "newsletter": 0
            },
            {
                "day": 1381874400,
                "greader": 10048,
                "other": 4153,
                "direct": 773,
                "newsletter": 0
            },
            {
                "day": 1381788000,
                "greader": 10052,
                "other": 4108,
                "direct": 733,
                "newsletter": 0
            },
            {
                "day": 1381701600,
                "greader": 10055,
                "other": 4228,
                "direct": 701,
                "newsletter": 0
            },
            {
                "day": 1381615200,
                "greader": 10062,
                "other": 4371,
                "direct": 650,
                "newsletter": 0
            },
            {
                "day": 1381528800,
                "greader": 10079,
                "other": 4474,
                "direct": 623,
                "newsletter": 0
            },
            {
                "day": 1381442400,
                "greader": 10112,
                "other": 4590,
                "direct": 584,
                "newsletter": 0
            },
            {
                "day": 1381356000,
                "greader": 10245,
                "other": 4789,
                "direct": 571,
                "newsletter": 0
            },
            {
                "day": 1381269600,
                "greader": 10150,
                "other": 5101,
                "direct": 585,
                "newsletter": 0
            },
            {
                "day": 1381183200,
                "greader": 10155,
                "other": 5255,
                "direct": 583,
                "newsletter": 0
            },
            {
                "day": 1381096800,
                "greader": 10172,
                "other": 5266,
                "direct": 554,
                "newsletter": 0
            },
            {
                "day": 1381010400,
                "greader": 10201,
                "other": 5247,
                "direct": 585,
                "newsletter": 0
            },
            {
                "day": 1380924000,
                "greader": 10232,
                "other": 5285,
                "direct": 582,
                "newsletter": 0
            },
            {
                "day": 1380837600,
                "greader": 10235,
                "other": 5349,
                "direct": 570,
                "newsletter": 0
            },
            {
                "day": 1380751200,
                "greader": 10267,
                "other": 5288,
                "direct": 556,
                "newsletter": 0
            },
            {
                "day": 1380664800,
                "greader": 10308,
                "other": 5042,
                "direct": 540,
                "newsletter": 0
            },
            {
                "day": 1380578400,
                "greader": 10328,
                "other": 4828,
                "direct": 551,
                "newsletter": 0
            },
            {
                "day": 1380492000,
                "greader": 10364,
                "other": 4630,
                "direct": 574,
                "newsletter": 0
            },
            {
                "day": 1380405600,
                "greader": 10350,
                "other": 4479,
                "direct": 597,
                "newsletter": 0
            }
        ],
        "code": 1
    }
    
    
    

    public by rosskevin modified Nov 10, 2016  33  0  1  0

    cucumber setup with docker chrome standalone

    cucumber setup with docker chrome standalone: driver.rb
    require 'selenium/webdriver'
    
    ###
    # Important details:
    #   - Capybara server is run on the host container at 0.0.0.0:4100
    #   - Test code determines the host's advertised IP address e.g. 172.1.1.1
    #   - Capybara Instructions execute on selenium/standalone-chrome container via api call to http://127.0.0.1:4444/wd/hub and gives it urls such as http://dummy.com.172.1.1.1.nip.io:4100 to visit the server on the host container.
    #   - This works on an OSX host with manually running the selenium container with docker run -p 4444:4444 selenium/standalone-chrome:3.0.1-germanium
    #
    #
    # Interaction (host ip 172.1.1.1)
    #   - host api call to selenium -> http://127.0.0.1:4444/wd/hub
    #   - selenium browser visit -> 172.1.1.1:4100
    #
    $remote = true
    $browser = :chrome
    # $browser = :firefox
    $wait_time = 5
    $default_driver = :selenium
    
    # establish capabilities
    desired_capabilities = begin
      if $browser == :firefox
        Selenium::WebDriver::Remote::Capabilities.firefox(loggingPrefs: {browser: 'ALL'})
      else
        # Tell selenium we want all messages by default - we'll sort them out with our own +ConsoleMessages+ class
        prefs = {
          # http://peter.sh/experiments/chromium-command-line-switches/
    
          # No change with the following
          # ----------------------------------
          # --js-flags="--max-old-space-size=500"
          # --disable-backing-store-limit
          # --diagnostics
          # --disable-extensions
          # --enable-leak-detection --crash-on-failure
    
          # Not yet tried but might be interesting
          # ---------------------------------------
          # --diagnostics
          # --disable-background-networking
          # --disable-background-timer-throttling
          # --disable-backing-store-limit
    
          #
          switches: %w(--disable-notifications --enable-leak-detection --crash-on-failure),
          loggingPrefs: {
            browser: 'ALL' #,
            # performance: 'ALL'
          },
          chromeOptions: {
            prefs: {
              credentials_enable_service: false, # disable saved passwords
              profile: {
                password_manager_enabled: false  # disable saved passwords
              }
            }
          }
        }
    
        Selenium::WebDriver::Remote::Capabilities.chrome(prefs)
      end
    end
    
    # For debugging selenium itself:
    # Selenium::WebDriver.logger.level = :debug
    if $remote == true
      # http://stackoverflow.com/questions/35821718/how-to-configure-capybara-to-run-tests-in-a-dockerized-selenium-grid
      Capybara.register_driver $default_driver do |app|
        # noinspection RubyArgCount
        Capybara::Selenium::Driver.new(app, {
          browser: :remote,
          url: 'http://127.0.0.1:4444/wd/hub', # selenium hub accessible url
          desired_capabilities: desired_capabilities
        })
      end
    else
      # Register chrome browser for the :selenium driver, can be triggered below with @show
      Capybara.register_driver $default_driver do |app|
        # noinspection RubyArgCount
        Capybara::Selenium::Driver.new(app, {
          browser: $browser,
          desired_capabilities: desired_capabilities
        })
      end
    end
    
    
    # Make the server available on the network.  default is 127.0.0.1 which is private
    Capybara.server_host = '0.0.0.0'
    Capybara.server_port = 4100
    Capybara.server = :puma
    cuke_log "Capybara running on #{Capybara.server_host}:#{Capybara.server_port} Process: #{Process.pid}"
    ENV['CIRCLE_NODE_INDEX'] = '9' unless ENV['CIRCLE_NODE_INDEX'].presence # default the node for local testing
    
    # first time around, we need this set.
    Capybara.default_driver = $default_driver
    Capybara.default_max_wait_time = $wait_time
    
    #
    # If the @show tag is present on a non-mac environment, ignore it,
    #   otherwise allow the combination of @javascript @show to trigger the
    #   :selenium driver (which is :chrome browser as configured above)
    #
    Before do |scenario|
      @scenario = scenario
      raise 'Scenario should not have @javascript tag, it really messes up truncation' if has_tag(scenario, '@javascript')
    
      # reset the default driver
      Capybara.current_driver = $default_driver
      Capybara.javascript_driver = $default_driver
      Capybara.default_max_wait_time = $wait_time # reset in case a scenario upped it
    
      # OLD, but if we need to exec a script to clear storage or cache, do it here.
      # page.driver.execute_script('window.localStorage.clear()')
    
      if should_show(scenario)
        # for some reason, just using the `using_driver` doesn't get us all the way there, so set/reset the `javascript_driver` as necessary.
        Capybara.current_driver = :selenium
        Capybara.javascript_driver = :selenium # needed for @show with chrome, as it doesn't seem to explicitly set the javascript driver
      end
      # cuke_log "Using #{Capybara.current_driver}/#{Capybara.javascript_driver}/#{Capybara.default_driver} wait: #{Capybara.default_max_wait_time}"
    end
    
    After do |scenario|
      # problem on @show with backgrounds: https://github.com/cucumber/cucumber/issues/52
      # cuke_log "Done #{Capybara.current_driver}/#{Capybara.javascript_driver}/#{Capybara.default_driver} - resetting driver and sessions."
      Capybara.use_default_driver
      Capybara.reset_sessions!
    end
    
    def selenium?
      Capybara.current_driver == :selenium
    end
    
    
    

    public by eg modified Sep 13, 2016  986  0  3  0

    HomeBrew Fix

    HomeBrew Fix : gistfile1.rb
    sudo brew doctor
    
    # Update HomeBrew
    
    cd /usr/local && \
    sudo git add . && \
    sudo git reset --hard HEAD && \
    sudo git pull --rebase
    
    #!/usr/bin/env ruby
    
    class CleaningHomeBrew
      
      BINARIES = ['cmake', 'imagemagick', 'jasper', 'jpeg', 'libevent', 'libtiff', 'little-cms','memcached','mysql','ossp-uuid','pidof','postgresql','redis','sphinx','wget']
      
      class << self
        
        def clean
          BINARIES.each { |binary| system "sudo brew cleanup && sudo brew link #{binary} && sudo brew uninstall #{binary} && sudo brew install #{binary}" }
        end
      end
    end
    
    begin
      CleaningHomeBrew.clean
    end
    
    

    public by Ricardo Silva modified Jan 27, 2016  395  0  3  0

    Extract contents of a .webarchive file.

    Extract contents of a .webarchive file.: unwebarchive.rb
    #!/usr/bin/env ruby
    #
    # Mac OS X webarchive is a binary format of a plist file. You can extract the contents manually:
    #  1. convert the plist file into XML by "plutil -convert xml1 file.webarchive"
    #  2. parse the resulted XML file by some XML parser
    #  3. decode "WebResourceData" by Base64.decode64(data) in each key
    #  4. save the decoded content into a file indicated by "WebResourceData"
    # Thankfully, the plist library can take care of annoying steps 2 and 3.
    #
    # Preparation:
    #  % gem install plist
    #
    # Usage:
    #  % unwebarchive.rb filename.webarchive
    #
    # Result:
    #  You'll find the extracted contents under the 'filename/' directory.
    #
    
    require 'rubygems'
    require 'fileutils'
    require 'plist'
    
    webarchive = ARGV.shift
    exportdir = File.basename(webarchive, ".webarchive")
    
    class UnWebarchive
    
      def initialize(webarchive, exportdir)
        @file = webarchive
        @dir  = exportdir
    
        prepare_exportdir
        parse_webarchive
      end
    
      def prepare_exportdir
        if File.exists?(@dir)
          print "Override existing export directory '#{@dir}' [Yes/No]? "
          exit 1 unless gets.chomp[/^y(es)?$/i]
        end
        FileUtils.mkdir_p(@dir)
        FileUtils.cp(@file, @dir)
      end
    
      def parse_webarchive
        FileUtils.cd(@dir) do
          system("plutil -convert xml1 #{@file}")
          plist = Plist.parse_xml(File.read(@file))
          file = plist["WebMainResource"]["WebResourceURL"]
          data = plist["WebMainResource"]["WebResourceData"].read
          data.gsub!(/file:\/\/\//, './')
          export(file, data)
          plist["WebSubresources"].each do |res|
            file = res["WebResourceURL"]
            data = res["WebResourceData"].read
            export(file, data)
          end
        end
      end
    
      def export(resource_uri, resource_data)
        if resource_uri[/^file:/]
          name = resource_uri.sub('file:///', '')
          puts "Writing '#{@dir}/#{name}' ..."
          File.open(name, "w") do |file|
            file.print resource_data
          end
        end
      end
    end
    
    UnWebarchive.new(webarchive, exportdir)
    
    
    

    public by tcyrus modified Jan 7, 2016  890  0  3  0

    Homebrew formula for jart/hiptext (https://github.com/jart/hiptext)

    Homebrew formula for jart/hiptext (https://github.com/jart/hiptext): hiptext.rb
    require "formula"
    
    class Hiptext < Formula
      homepage "https://github.com/jart/hiptext"
      head "https://github.com/jart/hiptext.git", :branch => "master"
    
      depends_on "pkg-config" => :build
      depends_on "ragel" => :build
      depends_on :libpng
      depends_on "jpeg"
      depends_on "ffmpeg"
      depends_on "freetype"
      depends_on "glog"
    
      patch :DATA
    
      #ENV["PKG_CONFIG_PATH"] = "#{HOMEBREW_PREFIX}/lib/pkgconfig:#{MacOS::X11.lib}/pkgconfig"
    
      #pkg-config --libs libavcodec libavformat libavutil libswscale
      def install
        system "make"
        system "install -m 0755 hiptext #{HOMEBREW_PREFIX}/bin"
      end
    end
    
    __END__
    diff --git a/font.cc b/font.cc
    index e3b3218..b9cf579 100644
    --- a/font.cc
    +++ b/font.cc
    @@ -11,7 +11,7 @@
     #include "graphic.h"
     #include "pixel.h"
    
    -DEFINE_string(font, "DejaVuSansMono.ttf",
    +DEFINE_string(font, "/System/Library/Fonts/Monaco.dfont",
                   "The path to the font .ttf file to use.");
     DEFINE_int32(font_index, 0, "Index of face to use inside font .ttf file.");
     DEFINE_int32(font_size, 11, "The size of the font in points.");
    diff --git a/hiptext.cc b/hiptext.cc
    index a23fa02..da0c96f 100644
    --- a/hiptext.cc
    +++ b/hiptext.cc
    @@ -202,9 +202,9 @@ int main(int argc, char** argv) {
       google::ParseCommandLineFlags(&argc, &argv, true);
       google::InitGoogleLogging(argv[0]);
       google::InstallFailureSignalHandler();
    -  const char* lang = std::getenv("LANG");
    -  if (lang == nullptr) lang = "en_US.utf8";
    -  std::locale::global(std::locale(lang));
    +  //const char* lang = std::getenv("LANG");
    +  //if (lang == nullptr) lang = "en_US.utf8";
    +  //std::locale::global(std::locale(lang));
       InitFont();
       Movie::InitializeMain();
    
    

    public by Rafael G modified Dec 12, 2015  10343  2  4  1

    WIP: script to auto-correct almost any program (the outputs should not contain "\n\n" though)

    WIP: script to auto-correct almost any program (the outputs should not contain "\n\n" though): examinator.rb
    ## Converting line endings to unix:
    inputs_file = File.open('./inputs.txt', 'a+')
    outputs_file = File.open('./outputs.txt', 'a+')
    
    input_file_contents = inputs_file.read.gsub(/\r\n?/,"\n")
    inputs_file.truncate(0)
    inputs_file.print input_file_contents
    
    outputs_file_contents = outputs_file.read.gsub(/\r\n?/,"\n")
    outputs_file.truncate(0)
    outputs_file.print outputs_file_contents
    
    inputs_file.close
    outputs_file.close
    
    #  Getting each input and each output into an array the idea is, basically, 
    # separate them each time we find an empty line ("\n").
    #  Should be noted though, that since the expected output should contain an
    # "\n" at its ending, so should each element on our array.
    
    inputs_file = File.open('./inputs.txt', 'r')
    outputs_file = File.open('./outputs.txt', 'r')
    
    inputs = []
    outputs = []
    
    loop do
      inputs_contents = inputs_file.gets('')
      outputs_contents = outputs_file.gets('')
      if inputs_contents.nil? || outputs_contents.nil?
        break
      else
        inputs_contents.gsub!("\n\n", "\n")
        outputs_contents.gsub!("\n\n", "\n")
        inputs << inputs_contents
        outputs << outputs_contents
      end
    end
    
    # To continue. Next step: get user's output.
    # Little snippet on how to get terminal's output below:
    
    test = __FILE__
    puts `ls #{test}`.class # It's a string.
    
    
    

    public by Drowze modified Dec 2, 2015  12665  0  4  0

    mim ajuda

    mim ajuda: mim_ajuda.rb
    require 'matrix'
    class Matrix
      def []=(i, j, x)
        @rows[i][j] = x
      end
    end
    
    class String # Only works for single letters; could be extended to uppercase letters too
      def step(c, delta=1)
        if c.ord + delta > 122 then
          return [c.ord + delta - 26].pack 'U'
        elsif c.ord + delta < 97 then
          return [c.ord + delta + 26].pack 'U'
        else
          return [c.ord + delta].pack 'U'
        end
      end
    
      def increment(c)
        return nil if self.size > 1
        c %= 26
        step self, c
      end
    
      def decrement(c)
        return nil if self.size > 1
        c %= 26
        step self, -c
      end
    end
    
    class Board
      attr_reader :cell_pairs
      MOVES = {
        'nw' => [-1, 0],
        'ne' => [-1, +1],
        'sw' => [+1, -1],
        'se' => [+1, 0]
      }
      CELL_CODES = Matrix[
        [0,0,0,0,0,1,3,3,3,2],
         [0,0,0,0,5,7,7,7,7,2],
          [0,0,0,5,7,7,7,7,7,2],
           [0,0,5,7,7,7,7,7,7,2],
            [0,5,7,7,7,7,7,7,7,2],
             [4,7,7,7,7,7,7,7,7,0],
              [4,7,7,7,7,7,7,7,0,0],
               [4,7,7,7,7,7,7,0,0,0],
                [4,7,7,7,7,7,0,0,0,0],
                 [4,7,7,7,7,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0,0,0]
      ]
    
      CELL_PAIRS = module Cell_pairs # "Function" to prepare the cell_pairs
        cell_pairs = Hash.new
        start_letter = 'a'
        increment = 0
        checker = 0
        CELL_CODES.each_with_index do |element, row, col|
          if row <= 5
            if checker != row then # I get here everytime it goes to another row
              increment = -row + 5
              checker = row
            end
            if(element == 7) then
              cell_pairs["#{row} #{col}"] = "#{row.to_s}#{start_letter.increment(increment)}"
              increment += 2
            end
          else
            if checker != row then # I get here everytime it goes to another row
              increment = row - 5
              checker = row
            end
            if(element == 7) then
              cell_pairs["#{row} #{col}"] = "#{row.to_s}#{start_letter.increment(increment)}"
              increment += 2
            end
          end
        end
        cell_pairs
      end
    
    
    
      def self.prepare_board positions
        seq = [' ',1,2,3,4,5,6,7,8,9,' ']
        counter = 0
        indentation = 0
        ret = ''
    
        CELL_CODES.to_a.map.with_index do |m, i|
          if i != 10 then
            ret += seq[counter].to_s + ' ' * indentation 
            m.each_with_index do |n, j| 
              n == 7 ? ret += ("#{positions[i,j]} ") : ret += ('  ')  # piece occupying the cell
              [4,5,6,7].include?(n) ? ret += ('| ') : ret += ('  ') 
            end
            ret += "\n" + ' ' * indentation unless i == CELL_CODES.to_a.map.size-1
            m.each_with_index do |n|
              [2,3,6,7].include?(n) ? ret += ('\\ ') : ret += ('  ') 
              [1,3,5,7].include?(n) ? ret += ('/ ') : ret += ('  ') 
            end
            ret += "\n" 
            counter+=1 
            indentation+=2
          end
        end
        ret += ' ' * 15 + 'a b c d e f g h i j k l m n o' + "\n"
        ret
      end
    end
    
    print Board::CELL_PAIRS
    
    

    public by DavidEGrayson modified Oct 1, 2015  9120  0  3  0

    Original: https://gist.github.com/pdg137/2cb48696ed7ba25370b6

    Original: https://gist.github.com/pdg137/2cb48696ed7ba25370b6: ruby_quiz1.rb
    a = 10
    
    def b(x = 1)
      10
    end
    
    puts a /2/
    5
    
    puts b /2/
    5
    
    puts a / 2/
    5
    
    puts b / 2/
    5
    
    
    
    

    public by addicttux modified Aug 27, 2015  10719  0  5  0

    PDF Template

    Template para la generación de reportes simples en PDF
    # Genera el reporte en PDF
    class NombreDeLaTablaEnSingularPdf < Prawn::Document
    
      include PdfHelper
    
      # Valores de inicialización del método.
      # @param nombre_de_la_tabla_en_singulars [Array] Contiene todos los registros a mostrar en el reporte
      # @param helpers [Obj] Utilizado para tener acceso a los helpers definidos en +app/helpers+
      # @note El encabezado y el título del reporte lo genera a través del código en +PdfHelper+ ubicado en +lib/pdf_helper.rb+
      def initialize( nombre_de_la_tabla_en_singulars, helpers )
        
        titulo =  'Listado de '
        encabezados    = %w( encabezado1 encabezado2 )
        ancho_columnas = [150,70]
        campos = Proc.new{|x| [x.campo_ordenado.titleize, x.campo_segundo.titleize] }
    
        super size: :letter,
              margin: 56,
              layout: :portrait
    
        pdf_encabezado_hoja_membretada
    
        pdf_titulo_del_reporte titulo
    
        #reporte
        elementos = [ encabezados ]
        elementos += nombre_de_la_tabla_en_singulars.map{|i| campos[i] }
        table elementos,
              column_widths: ancho_columnas,
              position: :center,
              cell_style: { size: 8 } do
          row(0).font_style = :bold
          row(0).align = :center
          row(0).size = 15
          self.row_colors = %w( EEEEEE FFE3BF )
          self.header = true
        end
    
      end
    
    end                                                                        

    public by addicttux modified Aug 27, 2015  10689  2  6  0

    TEST: xxx_test.rb

    Unit Testing
    require 'test_helper'
    
    class NombreDeTablaEnSingularTest < ActiveSupport::TestCase
    
      setup do
        @root = users :admin
        @usr  = users :user
        @caracteres_minimo = 
        @caracteres_maximo = 
        @palabra = ''
        @datos_1char          = { forma_de_pago: 'a',                      solo_root_ns: false, usuario_actual: @usr }
        @datos_blanco         = { forma_de_pago: '',                       solo_root_ns: false, usuario_actual: @usr }
        @datos_blanco_ambos   = { forma_de_pago: " #{@palabra} ",          solo_root_ns: false, usuario_actual: @usr }
        @datos_blanco_final   = { forma_de_pago: "#{@palabra} ",           solo_root_ns: false, usuario_actual: @usr }
        @datos_blanco_inicial = { forma_de_pago: " #{@palabra}",           solo_root_ns: false, usuario_actual: @usr }
        @datos_excedido       = { forma_de_pago: 'a'*@caracteres_maximo*2, solo_root_ns: false, usuario_actual: @usr }
        @datos_maximo         = { forma_de_pago: 'a'*@caracteres_maximo,   solo_root_ns: false, usuario_actual: @usr }
        @datos_minimo         = { forma_de_pago: 'a'*@caracteres_minimo,   solo_root_ns: false, usuario_actual: @usr }
        @datos_minusculas     = { forma_de_pago: @palabra.upcase,          solo_root_ns: false, usuario_actual: @usr }
        @datos_nulo           = { forma_de_pago: nil,                      solo_root_ns: false, usuario_actual: @usr }
        @datos_root           = { forma_de_pago: 'segundo',                solo_root_ns: true,  usuario_actual: @root }
        @datos_user           = { forma_de_pago: 'valor',                  solo_root_ns: false }
        @duplicado            = { forma_de_pago: '',                       solo_root_ns: false, usuario_actual: @usr }
      end
    
      # +-------------------------+
      # | Pruebas para New/Create |
      # +-------------------------+
    
      test 'Prueba #XXX-U-001: Probando la creación de ______ [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_user
        assert tut.valid?, tut.errors.messages.to_yaml
      end
    
      test 'Prueba #XXX-U-002: Probando que no guarde ______ en blanco [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_blanco
        refute tut.valid?, 'Se guardó en blanco'
      end
    
      test 'Prueba #XXX-U-003: Probando que no guarde ______ nil [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_nulo
        refute tut.valid?, 'Se guardó siendo nil'
      end
    
      test 'Prueba #XXX-U-004: Probando que no guarde ______ menores al mínimo de caracteres [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_1char
        refute tut.valid?, 'Se guardó siendo menor al mínimo de caracteres'
      end
    
      test 'Prueba #XXX-U-005: Probando que guarde ______ igual al mínimo de caracteres [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_minimo
        assert tut.valid?, 'No se guardo palabra igual al mínimo de caracteres'
      end
    
      test 'Prueba #XXX-U-006: Probando que guarde ______ igual al máximo de caracteres [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_maximo
        assert tut.valid?, 'No se guardo palabra igual al maximo de caracteres'
      end
    
      test 'Prueba #XXX-U-007: Prueba que no se guarde ______ mayor del máximo de caracteres permitidos [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_excedido
        refute tut.valid?, 'Se guardo palabra de mas caracteres que los permitidos'
      end
    
      test 'Prueba #XXX-U-008: Prueba que elimine el espacio inicial [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_blanco_inicial
        assert_equal tut.forma_de_pago, @palabra, 'No eliminó el espacio inicial'
      end
    
      test 'Prueba #XXX-U-009: Prueba que elimine espacios finales [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_blanco_final
        assert_equal tut.forma_de_pago, @palabra, 'No eliminó los espacios finales'
      end
    
      test 'Prueba #XXX-U-010: Prueba que elimine espacios iniciales y finales [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_blanco_ambos
        assert_equal tut.forma_de_pago, @palabra, 'No eliminó los espacios alrededor del texto'
      end
    
      test 'Prueba #XXX-U-011: Prueba que se guarde en minúsculas [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_minusculas
        assert_equal tut.forma_de_pago, @palabra, 'No guardó el texto en minúsculas'
      end
    
      test 'Prueba #XXX-U-012: Prueba que detecte contenido duplicado [hmjr]' do
        original = NombreDeTablaEnSingular.first.forma_de_pago
        @duplicado[:forma_de_pago] = original
        tut = NombreDeTablaEnSingular.create @duplicado
        refute tut.valid?, 'No detectó duplicidad'
      end
    
    
      # +----------------------+
      # | Pruebas para Destroy |
      # +----------------------+
    
      test 'Prueba #XXX-U-013: No debe de poder eliminar sin ser usuario registrado [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_user
        antes = NombreDeTablaEnSingular.count
        tut.destroy
        assert_equal antes, NombreDeTablaEnSingular.count, 'Borró pese a no estar registrado'
      end
    
      test 'Prueba #XXX-U-014: Elimina ______, el usuario no es root, solo_root_ns = false, no tiene dependientes [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_user
        tut.usuario_actual = @usr
        antes = NombreDeTablaEnSingular.count
        tut.destroy
        refute_equal antes, NombreDeTablaEnSingular.count, 'No se borró y no tiene teléfonos dependientes'
      end
    
      test 'Prueba #XXX-U-015: Elimina ______, el usuario no es root, solo_root_ns = false, TIENE dependientes [hmjr]' do
    #    tid = NombreDeTablaEnSingular.first
    #    dir = Directorio.create razon_fiscal: 'borrame s.a. de c.v.', razon_comercial: 'borrame', sobrenombre: 'borrame'
    #    TablaRelacionada.create tipo_forma_pago: tid, directorio: dir, solo_root_ns: false
    #    antes = NombreDeTablaEnSingular.count
    #    tid.usuario_actual = @usr
    #    tid.destroy
    #    assert_equal antes, NombreDeTablaEnSingular.count, 'Se eliminó pese a que tiene dependientes'
      end
    
    
      test 'Prueba #XXX-U-016: Elimina ______, el usuario no es root, solo_root_ns = true [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_root
        tut.usuario_actual = @usr
        antes = NombreDeTablaEnSingular.count
        tut.destroy
        assert_equal antes, NombreDeTablaEnSingular.count, 'Pudo borrar registro cuando solo root debería'
      end
    
      test 'Prueba #XXX-U-017: Elimina ______, el usuario es ROOT, solo_root_ns = false [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_user
        tut.usuario_actual = @root
        antes = NombreDeTablaEnSingular.count
        tut.destroy
        refute_equal antes, NombreDeTablaEnSingular.count, 'Root no pudo borrar un registro no exclusivo'
      end
    
      test 'Prueba #XXX-U-018: Elimina ______, el usuario es ROOT, solo_root_ns = true [hmjr]' do
        tut = NombreDeTablaEnSingular.create @datos_root
        antes = NombreDeTablaEnSingular.count
        tut.destroy
        refute_equal antes, NombreDeTablaEnSingular.count, 'Root no pudo borrar un registro exclusivo'
      end
    
      # +---------------------------------------+
      # | Pruebas para Edit para usuario normal |
      # +---------------------------------------+
    
      test 'Prueba #XXX-U-019: Probando la edición de ______ con usuario no logeado [hmjr]' do
        tut = NombreDeTablaEnSingular.last
        tut.update @datos_user
        refute tut.save, tut.errors.messages.to_yaml
      end
    
      test 'Prueba #XXX-U-020: Probando la edición de ______ con usuario logeado [hmjr]' do
        @datos_user[:usuario_actual] = @usr
        tut = NombreDeTablaEnSingular.first
        tut.update @datos_user
        assert tut.save, tut.errors.messages.to_yaml
      end
    
      test 'Prueba #XXX-U-021: Probando que no edite ______ en blanco [hmjr]' do
        tut = NombreDeTablaEnSingular.first
        tut.update @datos_blanco
        refute tut.valid?, 'Se guardó en blanco'
      end
    
      test 'Prueba #XXX-U-022: Probando que no edite ______ nil [hmjr]' do
        tut = NombreDeTablaEnSingular.first
        tut.update @datos_nulo
        refute tut.valid?, 'Se guardó siendo nil'
      end
    
      test 'Prueba #XXX-U-023: Probando que no edite ______ menores al mínimo de caracteres [hmjr]' do
        tut = NombreDeTablaEnSingular.first
        tut.update @datos_1char
        refute tut.valid?, 'Se guardó siendo menor al mínimo de caracteres'
      end
    
      test 'Prueba #XXX-U-024: Probando que guarde ______ siendo igual al mínimo de caracteres [hmjr]' do
        tut = NombreDeTablaEnSingular.first
        tut.update @datos_minimo
        assert tut.valid?, 'No se guardo palabra igual al mínimo de caracteres'
      end
    
      test 'Prueba #XXX-U-025: Probando que guarde ______ igual al máximo de caracteres [hmjr]' do
        tut = NombreDeTablaEnSingular.first
        tut.update @datos_maximo
        assert tut.valid?, 'No se guardo palabra igual al máximo de caracteres'
      end
    
      test 'Prueba #XXX-U-026: Prueba que no se guarde ______ mayor al máximo de caracteres [hmjr]' do
        tut = NombreDeTablaEnSingular.first
        tut.update @datos_excedido
        refute tut.valid?, 'Se guardo palabra mayor al máximo de caracteres'
      end
    
      test 'Prueba #XXX-U-027: Prueba que elimine el espacio inicial [hmjr]' do
        tut = NombreDeTablaEnSingular.first
        tut.update @datos_blanco_inicial
        assert_equal tut.forma_de_pago, @palabra, 'No eliminó el espacio inicial'
      end
    
      test 'Prueba #XXX-U-028: Prueba que elimine espacios finales [hmjr]' do
        tut = NombreDeTablaEnSingular.first
        tut.update @datos_blanco_final
        assert_equal tut.forma_de_pago, @palabra, 'No eliminó los espacios finales'
      end
    
      test 'Prueba #XXX-U-029: Prueba que elimine espacios iniciales y finales [hmjr]' do
        tut = NombreDeTablaEnSingular.first
        tut.update @datos_blanco_ambos
        assert_equal tut.forma_de_pago, @palabra, 'No eliminó los espacios alrededor del texto'
      end
    
      test 'Prueba #XXX-U-030: Prueba que se guarde en minúsculas [hmjr]' do
        tut = NombreDeTablaEnSingular.first
        tut.update @datos_minusculas
        assert_equal tut.forma_de_pago, @palabra, 'No guardó el texto en minúsculas'
      end
    
      test 'Prueba #XXX-U-031: Prueba que detecte contenido duplicado [hmjr]' do
        tut = NombreDeTablaEnSingular.first
        tut.update forma_de_pago: NombreDeTablaEnSingular.last.forma_de_pago, usuario_actual: @usr
        refute tut.valid?, 'No detectó duplicidad'
      end
    
      test 'Prueba #XXX-U-032: Prueba que NO pueda editar si solo_root_ns es true [hmjr]' do
        tut = NombreDeTablaEnSingular.create forma_de_pago: @palabra, solo_root_ns: true, usuario_actual: @usr
        cam = NombreDeTablaEnSingular.find tut.id
        cam.forma_de_pago = 'cambiado'
        cam.usuario_actual = @usr
        refute cam.save, 'No detectó que solo root lo puede modificar'
      end
    
      # +-------------------------------------+
      # | Pruebas para Edit para usuario root |
      # +-------------------------------------+
    
      test 'Prueba #XXX-U-033: Probando la edición de ______ con usuario logeado [hmjr]' do
        @usr = @root
        tut = NombreDeTablaEnSingular.last
        tut.update @datos_root
        assert tut.save, tut.errors.messages.to_yaml
      end
    
      test 'Prueba #XXX-U-034: Probando que no edite ______ en blanco [hmjr]' do
        tut = NombreDeTablaEnSingular.last
        tut.update @datos_blanco
        refute tut.valid?, 'Se guardó en blanco'
      end
    
      test 'Prueba #XXX-U-035: Probando que no edite ______ nil [hmjr]' do
        tut = NombreDeTablaEnSingular.last
        tut.update @datos_nulo
        refute tut.valid?, 'Se guardó siendo nil'
      end
    
      test 'Prueba #XXX-U-036: Probando que no edite ______ menores al mínimo de caracteres [hmjr]' do
        tut = NombreDeTablaEnSingular.last
        tut.update @datos_1char
        refute tut.valid?, 'Se guardó siendo menor al mínimo de caracteres'
      end
    
      test 'Prueba #XXX-U-037: Probando que guarde ______ igual al mínimo de caracteres [hmjr]' do
        tut = NombreDeTablaEnSingular.last
        tut.update @datos_minimo
        assert tut.valid?, 'No se guardo palabra igual al mínimo de caracteres'
      end
    
      test 'Prueba #XXX-U-038: Probando que guarde ______ igual al máximo de caracteres [hmjr]' do
        tut = NombreDeTablaEnSingular.last
        tut.update @datos_maximo
        assert tut.valid?, 'No se guardo palabra igual al máximo de caracteres'
      end
    
      test 'Prueba #XXX-U-039: Prueba que no se guarde ______ mayor al máximo de caracteres [hmjr]' do
        tut = NombreDeTablaEnSingular.last
        tut.update @datos_excedido
        refute tut.valid?, 'Se guardo palabra mayor al máximo de caracteres'
      end
    
      test 'Prueba #XXX-U-040: Prueba que elimine el espacio inicial [hmjr]' do
        tut = NombreDeTablaEnSingular.last
        tut.update @datos_blanco_inicial
        assert_equal tut.forma_de_pago, @palabra, 'No eliminó el espacio inicial'
      end
    
      test 'Prueba #XXX-U-041: Prueba que elimine espacios finales [hmjr]' do
        tut = NombreDeTablaEnSingular.last
        tut.update @datos_blanco_final
        assert_equal tut.forma_de_pago, @palabra, 'No eliminó los espacios finales'
      end
    
      test 'Prueba #XXX-U-042: Prueba que elimine espacios iniciales y finales [hmjr]' do
        tut = NombreDeTablaEnSingular.last
        tut.update @datos_blanco_ambos
        assert_equal tut.forma_de_pago, @palabra, 'No eliminó los espacios alrededor del texto'
      end
    
      test 'Prueba #XXX-U-043: Prueba que se guarde en minúsculas [hmjr]' do
        tut = NombreDeTablaEnSingular.last
        tut.update @datos_minusculas
        assert_equal tut.forma_de_pago, @palabra, 'No guardó el texto en minúsculas'
      end
    
      test 'Prueba #XXX-U-044: Prueba que detecte contenido duplicado [hmjr]' do
        tut = NombreDeTablaEnSingular.last
        tut.update forma_de_pago: NombreDeTablaEnSingular.first.forma_de_pago, usuario_actual: @root
        refute tut.valid?, 'No detectó duplicidad'
      end
    
      test 'Prueba #XXX-U-045: Prueba que pueda editar si solo_root_ns es true [hmjr]' do
        tut = NombreDeTablaEnSingular.create forma_de_pago: @palabra, solo_root_ns: true, usuario_actual: @root
        cam = NombreDeTablaEnSingular.find tut.id
        cam.forma_de_pago = 'cambiado'
        cam.usuario_actual = @root
        assert cam.save, 'No detectó que solo root lo puede modificar'
      end
    
    end
    
    #------------------------------------------------------------------------------
    # NombreDeTablaEnSingular
    #
    # Name          SQL Type             Null    Default Primary
    # ------------- -------------------- ------- ------- -------
    # id            int(11)              false           true
    # forma_de_pago varchar(10)          false           false
    # solo_root_ns  tinyint(1)           false   0       false
    # lock_version  int(11)              false   0       false
    # created_at    datetime             false           false
    # updated_at    datetime             false           false
    #
    #------------------------------------------------------------------------------
    
    • Public Snippets
    • Channels Snippets