text
stringlengths
10
2.61M
require 'erb' class ShowExceptions attr_reader :app def initialize(app) @app = app end def call(env) begin app.call(env) rescue => e res = Rack::Response.new content = render_exception(e) res.status = 500 res.write(content) res["Content-type"] = "text/html" ...
SpEventApi::Application.routes.draw do namespace :api do namespace :v1 do get 'all_events' => 'events#all_events' get 'spn_events' => 'events#spn_events' get 'tech_omaha_events' => 'events#tech_omaha_events' get 'startup_lincoln_events' => 'events#startup_linco...
class TransactionsController < ApplicationController def create @transaction = Transaction.create(transaction_params) @flurbo = Flurbo.where(user: @transaction.user).first || Flurbo.create(user: @transaction.user, balance: Flurbo::DEFAULT_BALANCE) new_balance = @flurbo.balance - @transaction.amoun...
#!/usr/bin/ruby def has(n, s) counts = {} s.chars.each do |c| counts[c] = if counts[c] counts[c] + 1 else 1 end end counts.values.include? n end ids = DATA.read.split("\n") doubles = ids.select { |id| has(2, id) } triples = ids.select { |id| has(3, id) } checksum = doubles.length * triples.length put...
class Scout < ActiveRecord::Base attr_accessible :den_id, :first_name, :last_name, :address1, :address2, :city, :state, :zipcode, :parent_email1, :parent_email2, :picture validates_presence_of :first_name, :last_name validates_presence_of :den_id, :message => "must select a den" belongs_to :den has_and_...
class MessageTopic < ActiveRecord::Base belongs_to :user belongs_to :message_user,:class_name=> "User",:foreign_key => "message_user_id" belongs_to :last_message_post,:class_name=> "MessagePost",:foreign_key => "last_message_post_id" has_many :message_posts validates_presence_of :user_id validates_presen...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable validates :username, presence: true, uniqueness: true,...
module StructPacking private # Common defines for Packable and Unpackable module Base private def self.included(base) base.extend ClassMethods base.attr_mapped_struct base.instance_eval { @selfclass = base } base.instance_eval { def selfclass ; @selfclass ;...
require 'puppet' require 'puppet/type/mac_web_proxy' describe Puppet::Type.type(:mac_web_proxy) do let(:resource) do Puppet::Type.type(:mac_web_proxy).new( name: 'wi-fi', proxy_server: 'http://proxy.myorg.com', proxy_port: '8088', ) end it 'is ensurable' do resource[:ensure] = :pre...
module OpenAgent module Message module SIF_Register class SIF_Application include ROXML xml_name 'SIF_Application' xml_accessor :sif_vendor, :from => 'SIF_Vendor' xml_accessor :sif_product, :from => 'SIF_Product' xml_accessor :sif_version, :from => 'SIF_Version' ...
# Let's define a tree and binary tree to demonstrate the pattern matching abilities. Tree = Algebrick.type do |tree| variants Empty = type, Leaf = type { fields Integer }, Node = type { fields tree, tree } end # => Tree(Empty | Leaf | Node) Binar...
class BillsController < ApplicationController before_filter :must_be_logged_in def index @bills = @auth.bills.order(:day) end def new @bill = Bill.new end def create bill = Bill.create(params[:bill]) @auth.bills << bill redirect_to(bills_path) end private def must_be_logged_in redirect_to(ro...
class Shelter < ApplicationRecord has_many :pets, dependent: :destroy validates_presence_of :name, :address, :city, :state, :zip def self.sort all.sort_by(&:name) end end
class AddIcseExamCategoryIdToExamGroup < ActiveRecord::Migration def self.up add_column :exam_groups, :icse_exam_category_id, :integer end def self.down remove_column :exam_groups, :icse_exam_category_id end end
# One user can enter a word (or phrase, if you would like your game to support that), and another user attempts to guess the word. # Guesses are limited, and the number of guesses available is related to the length of the word. # Repeated guesses do not count against the user. # The guessing player receives continual f...
# typed: strict # frozen_string_literal: true module Ffprober module Ffmpeg class Version extend T::Sig sig { params(ffprobe_exec: T.any(Ffprober::Ffmpeg::Exec, T.untyped)).void } def initialize(ffprobe_exec = Ffprober::Ffmpeg::Exec.new) @ffprobe_exec = ffprobe_exec @version = ...
# frozen_string_literal: true module BoltSpec module Plans class TaskStub < ActionStub def matches(targets, _task, arguments, options) if @invocation[:targets] && Set.new(@invocation[:targets]) != Set.new(targets.map(&:name)) return false end if @invocation[:arguments] &&...
source 'https://rubygems.org' ruby '2.3.1' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 5.0.0' # Use postgresql as the database for Active Record gem 'pg', '~> 0.18' # Use Puma as the app server gem 'puma', '~> 3.0' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' # Use Uglifie...
require 'minitest/autorun' require 'minitest/pride' require 'faraday' require './lib/server' class ServerTest < Minitest::Test # test_it_exists leaves the connection open; the rest must be run one at a time, with a new server opened for each test def test_it_exists skip server = Server.new assert_i...
class Comment < ActiveRecord::Base belongs_to :recipe validates_presence_of :comment validates_presence_of :recipe_id end
class DynamicRecord::Field < DynamicRecord::Base self.table_name = :dynamic_record_fields belongs_to :value_field, :foreign_key => :value_id, :foreign_type => :value_type, :dependent => :destroy, :polymorphic => true attr_accessible :value, :field_description belongs_to :record bel...
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'daggregator/model' describe Daggregator::Model::GraphBuilder do subject { Daggregator::Model::GraphBuilder.new } describe "initialize" do its(:identifier_proc) { should be_true } its(:keys) {should be_true } its(:flows_to...
class Dish < ActiveRecord::Base belongs_to :local validates_presence_of :name, :price acts_as_taggable_on :styles end
# Source: https://launchschool.com/exercises/b5c55bc6 def twice(num) return num * 2 unless num.to_s.size.even? # odd len = num.to_s.size first_half = num.to_s[0..(len/2) - 1] return num * 2 unless num == (first_half * 2).to_i num end puts twice(37) == 74 puts twice(44) == 44 puts twice(334433) == 668866 put...
class FixedArray def initialize(size = 16) @array = Array.new(size, nil) end def size @array.length end def get(index) raise IndexOutOfBoundsError if index >= self.size || index < 0 @array[index] end def set(index, value) raise IndexOutOfBoundsError if index >= self.size || index < ...
class Post < ActiveRecord::Base validates :title , presence: true validates :content, length: {minimum: 100} validates :category, inclusion: {in: ["Fiction", "Non-Fiction"]} end
#!/usr/local/bin/ruby -w require "graphics" class Ball < Graphics::Body COUNT = 50 G = V[0, -18 / 60.0] attr_accessor :g def initialize w super self.a = random_angle / 2 self.m = rand 25 self.g = G end def draw w.angle x, y, a, 10+3*m, :red w.circle x, y, 5, :white, :filled ...
# Welcome puts "" puts "Welcome to the loan calculator" # Menu def menu puts "" puts "Would you like to use the mortage calculator? (Y/N)" gets.chomp.upcase end # Calculator def calc # Inputs print "Input loan amount in $: " amount = gets.to_i print "Input the length of loan in years: " years = get...
require 'test_helper' class MenuItemTest < ActiveSupport::TestCase def setup @menu_item = MenuItem.create(type_id: 1, shop_id: 1) end test "shop id must be present" do assert @menu_item.valid? end end
Sequel.migration do up do create_table(:characters) do primary_key :id, :null=>false foreign_key :user_id, :null=>false String :name, :null=>false, :unique=>true end end down do drop_table(:characters) end end
# frozen_string_literal: true module Dry module Logic VERSION = "1.5.0" end end
data_bag = Chef::EncryptedDataBagItem.load('password','redmine') redmine_password = data_bag['password'] execute "create-redminedb" do command "mysql -uroot < #{Chef::Config[:file_cache_path]}/create-redminedb.sql" action :nothing end template "database.sql" do path "#{Chef::Config[:file_cache_path]}/create-re...
class Dish attr_accessor :name, :dish_id , :cuisine , :sum @@all = [ ] def initialize (name:, dish_id:, cuisine:, sum:) @name = name @dish_id = dish_id @cuisine = cuisine @sum = sum @@all << self end def self.all @@all end def self.find_by_cuisine(cuisine) self.all.select {...
=begin The device on your wrist beeps several times, and once again you feel like you're falling. "Situation critical," the device announces. "Destination indeterminate. Chronal interference detected. Please specify new target coordinates." The device then produces a list of coordinates (your puzzle input). Are they ...
require 'rails_helper' RSpec.describe User, type: :model do let(:user) { create(:user) } describe "invalid user" do let(:user_with_invalid_name) { build(:user, name: "") } let(:user_with_invalid_email) { build(:user, email: "") } end end
require 'test/unit' require File.dirname(__FILE__) + '/../conf/include' require 'author_detective.rb' require 'time' class MediaWikiApiTest < Test::Unit::TestCase def setup @db = SQLite3::Database.new(":memory:") @db.execute('CREATE TABLE irc_wikimedia_org_en_wikipedia ( id integer primary key autoincrement...
module DocumentTemplatesHelper def render_document_template(body) renderer = Redcarpet::Render::HTML.new markdown = Redcarpet::Markdown.new(renderer, no_intra_emphasis: true) markdown.render(body).html_safe end def available_fields @company.fields.joins(:form).where.not(forms: {name: 'conditions'...
#lib/introduction.rb def introduction(name) puts "Hello there, my name is #{name}" end
def max_counter(n, a) array = [0]*n a = remove_redundant_max_counters(n, a) return array if a.empty? return increment_counters_for_array_with_no_max_counters(a, array) unless a.include?(n+1) max_counters = get_array_indices_of_max_counters(n, a) max_counter_ranges = get_range_between_max_counter_elements...
require 'csv' require_relative 'item' require 'pry' class ItemRepository # shared behaviors between item & merchant repos can be pulled to module? attr_reader :all, :parent def initialize(file_path, parent) contents = CSV.open(file_path, headers: true, header_converters: :symbol) @all = cont...
class CreateStatistics < ActiveRecord::Migration def change create_table :statistics do |t| t.integer :all_reports t.integer :ut_reports t.integer :mt_reports t.integer :pt_reports t.integer :rt_reports t.integer :et_reports t.integer :gt_reports t.string :most_acti...
require 'rails_helper' include AdminHelpers RSpec.feature 'Creating recruitment by H.R' do before do @hr = create(:hr) login_as(@hr, scope: :hr) assign_permission(@hr, :read, Recruitment) assign_permission(@hr, :create, Recruitment) visit new_admin_recruitment_path end scenario 'with valid d...
class Product < ActiveRecord::Base belongs_to :product_category has_many :inventory_items has_many :users, through: :inventory_items end
class ChangeCentsAttributesToIntegers < ActiveRecord::Migration def change change_column :cash_expenses, :invoice_cents, :integer change_column :cash_revenues, :invoice_cents, :integer change_column :cash_revenues, :arpu_cents, :integer change_column :transactions, :planned_cents, :integer change_...
require 'brew_sparkling/location' module BrewSparkling module Recipe module Extension module Path def build_path Location.build_path.join(name, version) end def archive_path Location.archive_path.join(name, version) end def info_plists ...
module Spree class SalesTaxReport < Spree::Report HEADERS = { months_name: :string, zone_name: :string, sales_tax: :integer } SEARCH_ATTRIBUTES = { start_date: :taxation_from, end_date: :taxation_till } SORTABLE_ATTRIBUTES = [] def no_pagination? true end def generate(options = {}) ...
require 'rails_helper' RSpec.describe Post, type: :model do let(:post) { create(:post) } it 'ファクトリーが有効かどうか' do expect(post).to be_valid end it 'ユーザーと関連づけられているか' do post = build(:post, user_id: nil) expect(post).not_to be_valid end it '最新の投稿を最初に表示する' do create(:post, :yesterday) creat...
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::DataDogTracing do module DataDogTest class Thing < GraphQL::Schema::Object field :str, String def str "blah" end end class Query < GraphQL::Schema::Object include GraphQL::Types::Relay::HasNo...
class EmployeeDatatable < AjaxDatatablesRails::Base # include AjaxDatatablesRails::Extensions::WillPaginate def sortable_columns # Declare strings in this format: ModelName.column_name @sortable_columns ||= ['employees.city'] #Employee.first_name end def searchable_columns # Declare strings in thi...
require 'Bike' describe Bike do let(:test_bike1) { Bike.new("test_bike1") } it 'checks if it is working' do expect(test_bike1).to respond_to(:working?) expect(test_bike1.working?).to eq true end it 'can be reported as broken' do expect(test_bike1).to respond_to(:report_broken) expect(test_bik...
require 'chemistry/element' Chemistry::Element.define "Tin" do symbol "Sn" atomic_number 50 atomic_weight 118.710 melting_point '505.21K' end
require 'fileutils' require 'json' module Fakebook module Cache class Persist def initialize(key, response) @key = key.gsub('"', '') @response = response @path = File.join(Fakebook::Cache.cache_directory, Fakebook.cache_subfolder) end def save unless File.direc...
module ApplicationHelper TIPS = [ "Use the progress bar to seek.", "Use <kbd>M</kbd> to mute or unmute.", "Use <kbd>space</kbd> to pause and play.", "Use <kbd>J</kbd> and <kbd>K</kbd> to navigate songs.", "Use <kbd>up</kbd> and <kbd>down</kbd> to adjust the volume." ].freeze def csrf_meta_tags ...
module SolitaireCipher class Deck def initialize deck = nil @deck = deck == nil ? (1..52).to_a << :JOKER_A << :JOKER_B : deck end def next_number move_jokers triple_cut count_cut character = @deck[0].respond_to?(:+) ? @deck[0] : 53 @deck[character].respond_to?(:+) ? @...
require 'pry' require 'pry-byebug' class Person # this class will likely be simple, and just remember its name attr_accessor :first_name def initialize(first_name) @first_name = first_name end end
module Vagrant module Butcher module Helpers module Guest def windows?(env) machine(env).guest.capability_host_chain.last.first == :windows end def get_guest_key_path(env) return butcher_config(env).guest_key_path unless butcher_config(env).guest_key_path == :DE...
class ChangeIngredientDescription < ActiveRecord::Migration[5.2] def up change_column :ingredients, :description, :text, null: false, limit: 200 change_column :ingredients, :name, :string, null: false, limit: 50 end def down # Put here so I could add more functionallity to a single migration end en...
class Pt < AbstractReport has_one :report, as: :specific, dependent: :destroy has_many :pt_defects, dependent: :destroy attr_accessible :light, :uv_light, :penetration_time, :developer_time, :batch, :dye_product, :dev_product, :cleaner_product, :pre_clean, :report_attributes, :temperature, ...
Given /^I have included the .* script$/ do #pending end Then /^I should see that JQuery is available$/ do fail "JQuery not available" if $browser.execute_script <<-JS return typeof jQuery == 'undefined' JS end Then /^I should see that JQuery has been extended with a 'detectCard' method$/ do fail "JQuery n...
class AddUserIdToPatientLists < ActiveRecord::Migration def change add_column :patient_lists, :user_id, :integer add_index :patient_lists, :user_id end end
require 'nokogiri' require 'open-uri' require 'parallel' class CompanyInfo def initialize(ticker_code) @base_url = "http://stocks.finance.yahoo.co.jp/stocks" @ticker_code = ticker_code scrape end attr_reader :name, :ticker_code, :category, :unit, :recent_high_price, :recent_low_price, :high_price, ...
require 'test_helper' class DiagnosticAmiantesControllerTest < ActionController::TestCase setup do @diagnostic_amiante = diagnostic_amiantes(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:diagnostic_amiantes) end test "should get new" do ...
module Recurly module Verification def stringify_keys data Hash[data.map { |k, v| [k.to_s, v] }] end class PreEscapedString < String end def digest_data(data) if data.is_a? Array return nil if data.empty? PreEscapedString.new( '[%s]' % data.map{|v|digest_data(v)}.co...
Pod::Spec.new do |s| s.name = "DropboxBrowser" s.version = "v5.1"" s.summary = "Dropbox Browser provides a simple and effective way to browse, view, and download files using the iOS Dropbox SDK." s.homepage = "https://github.com/danielbierwirth/DropboxBrowser" s.license = { :type =...
# -*- encoding : utf-8 -*- class PageRevision < ActiveRecord::Base CONTENT_TYPES = %w(html markdown).freeze validates_presence_of :page validates_inclusion_of :content_type, in: CONTENT_TYPES, message: "Invalid content type" belongs_to :page belongs_to :member default_scope order(:version) end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :project_list def project_list @project_list = Project.all.order(:rank) if params['id'] != ni...
class RemoveTitleFromNewsItems < ActiveRecord::Migration def change remove_column :news_items, :title end end
require_relative 'table' class User < Table def self.find_by_id(id) user_hash = $db.execute(<<-SQL, :user_id => id).first SELECT users.* FROM users WHERE users.id = :user_id SQL User.new(user_hash) end def self.find_by_name(fname, lname) user_hash = $db...
module Sumac # Raised by the remote endpoint when trying to call a method that does not exist or has not been exposed. class UnexposedMethodError < Error def initialize(message = 'method is not defined or has not been exposed') super end end end
module MCollective module Util module IPTables class IPv6<IPv4 def configure @iptables_cmd = Config.instance.pluginconf.fetch("iptables.ip6tables", "/sbin/ip6tables") @logger_cmd = Config.instance.pluginconf.fetch("iptables.logger", "/usr/bin/logger") @chain = Config.in...
module Achiever module Generators class MigrationGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) def generate_migration copy_file "migration.rb", "db/migrate/create_achiever_table.rb" end end end end
class Project < ActiveRecord::Base has_many :tasks belongs_to :client validates_presence_of :name, :client_id, :start_date, :end_date validates_numericality_of :client_id validate :check_date private def check_date if self.end_date < self.start_date self.errors.add(errors: "the date you are giving doesn't...
class CreateDrivers < ActiveRecord::Migration def change create_table :drivers do |t| t.integer :user_id t.integer :dni t.string :license, limit: 10 t.string :car_plate, limit: 7 t.string :car_type, limit: 10 t.string :car_brand, limit: 20 t.string :car_model, limit: 20 ...
class SearchDocument < ActiveRecord::Base include SearchRebuilder include FullTextSearchable self.table_name = 'pg_search_documents' VALID_SEARCHABLE_TYPES = { posts: 'Post', learning_tracks: 'LearningTrack', users: 'User', blog_articles: 'BlogArticle', educational_institutions: 'Educatio...
require_relative '../../app/models/email' describe Email do subject { Email.new("me@me.com", ["test@test.com"], "Subject", "body test") } it "return 0 when nobody have downloaded it" do subject.downloaded_times.should == 0 end it "#all_users_downloaded? return false when nobody have downloaded it" do ...
class FontAurulentNerdFont < Formula version "2.3.3" sha256 "963ce11f65171cc8d368c69af5ed2d1684141b35863a24f4c23f1870cc73b098" url "https://github.com/ryanoasis/nerd-fonts/releases/download/v#{version}/AurulentSansMono.zip" desc "AurulentSansMono Nerd Font (Aurulent Sans Mono)" desc "Developer targeted fonts ...
# Favicon設定用のプロジェクトカスタムフィールドを作成 class CreateProjectFaviconCustomField < ActiveRecord::Migration include Redmine::I18n def change settings = Setting.plugin_redmine_project_favicon || {} condisions = ['name = ?', l(:name_project_favicon_custom_field)] custom_field = ProjectCustomField.find(:first, :con...
class DeleteColumnsFromImages < ActiveRecord::Migration def change remove_column :images, :created_at, :timestamps remove_column :images, :updated_at, :timestamps end end
class SkillsController < ApplicationController def create @user = User.find(user_id_params[:user_id]) if Skill.exists?(name: create_params[:name]) @skill = Skill.find_by(create_params) if UsersSkill.exists?(user_id: user_id_params, skill_id: @skill) @skills = @user.skills.order("rec...
# frozen_string_literal: true require "mixlib/cli" unless defined?(Mixlib::CLI) module Kafkat module Command class NotFoundError < StandardError; end class InvalidCommand < StandardError; end class InvalidArgument < StandardError; end def self.categories registered.uniq { |h| h[:category] } ...
module Mongoid module Shell module Commands class Mongoexport < Mongoid::Shell::Commands::Base include Mongoid::Shell::Properties::Host include Mongoid::Shell::Properties::Database include Mongoid::Shell::Properties::Username include Mongoid::Shell::Properties::Password ...
#!/usr/bin/env ruby # :title: PlanR::Document::Note =begin rdoc (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org> =end require 'plan-r/document' module PlanR =begin rdoc A Note document =end class NoteDocument < Document def self.node_type :note end def self.default_properties p...
=begin combine_arrays Write a method that takes two sorted arrays and produces the sorted array that combines both. Restrictions: Do not call sort anywhere. Do not in any way modify the two arrays given to you. Do not circumvent (2) by cloning or duplicating the two arrays, only to modify the copies. Hint:...
# frozen_string_literal: true module EasyMonitor module Util module Errors class HighQueueNumberError < StandardError def initialize(msg = 'Queue is too high', service_name = nil) msg += " for service #{service_name}" if service_name super(msg) end end end en...
# frozen_string_literal: true module CommentsHelper def render_comment(user_post) render partial: 'comment_post', collection: @comments, locals: { user_post: user_post } end end
class GenericParser def initialize(source, type) @type = type @source = source @all_items = [] @mechanize = Mechanize.new() @values = build_hash_of_attributes end def get_products (1..last_page).each_with_object(@all_items) { |p, list| parse_items(p, list)}.uniq rescue Exception => e ...
require 'test_helper' class ImagepostsControllerTest < ActionController::TestCase setup do @imagepost = imageposts(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:imageposts) end test "should get new" do get :new assert_response :succ...
require "test_helper" require "nokogiri" class ActiveServerTest < VitaeServerTestCase test "the homepage contains lists the cvs we're hosting" do with_project :dkaz do get '/' assert last_response.ok? assert_matches %w[Katya Derek Arthur Zeena] assert_select "a[href='/katya']", "Katya" ...
require "erb" # We pass the current context in as 'binding' so the template will lookup methods here # This class will function as the context for the template - the template will lookup all methods and ivars on this class class EoinView def initialize @greeting = "Yo!" end def name "eoin" end ...
#!/usr/bin/env ruby require 'rubygems' require 'need' require 'active_support/inflector' need{'sweet_destroyer'} module TestSweet class PageDestroyer < SweetDestroyer def initialize(*args) @site, @name = args unless @name && @site raise ArgumentError, 'you must provide a site and a page' ...
When /^I submit valid email and password$/ do fill_in "Email", with: @user.email fill_in "Password", with: "secret" fill_in "Password confirmation", with: "secret" click_button "commit" @user = User.find_by_email(@user.email) end When /^I click the facebook link$/ do OmniAuth.config.mock_auth[:faceboo...
class CreateSuggestedTrackIdentifications < ActiveRecord::Migration[6.1] def change create_table :suggested_track_identifications do |t| t.references :tracklist_track, :null => false, foreign_key: true # TODO Check the alias of identifier to users running properly with db constraints t.reference...
require File.dirname(__FILE__) + '/../spec_helper' describe "NotificationGenerator" do describe "generating new_comment" do before(:all) do Rails::Generator::Scripts::Generate.new.run(["notification", "new_comment"], :destination => fake_rails_root) @new_files = file_list end it "should gene...
class AddProductToImages < ActiveRecord::Migration[6.0] def change add_belongs_to :images, :product end end
class AddAttachmentsTutorialVideoToTutorialVideo < ActiveRecord::Migration def self.up add_column :tutorial_videos, :tutorial_video_file_name, :string add_column :tutorial_videos, :tutorial_video_content_type, :string add_column :tutorial_videos, :tutorial_video_file_size, :integer add_column :tutoria...
module OpenAssets module Cache class SSLCertificateCache < SQLiteBase def initialize path = OpenAssets.configuration ? OpenAssets.configuration[:cache] : ':memory:' super(path) end def setup db.execute <<-SQL CREATE TABLE IF NOT EXISTS SslCertificate( ...
# num_of_hotdogs_eaten = 3 # while num_of_hotdogs_eaten < 10 # num_of_hotdogs_eaten += 2 # puts "You have now eaten #{num_of_hotdogs_eaten} hot dog(s)." # end # puts "You ate a total of #{num_of_hotdogs_eaten} hot dogs!" counter = 0 until counter == 20 puts "The current number is less than 20." ...
class Review < ActiveRecord::Base belongs_to :driver belongs_to :user # belongs_to :notification default_scope -> { order('created_at DESC') } validates :comment, length: { maximum: 140 } end
# Not sure might be class ExampleMailer < ApplicationMailer::Base class ExampleMailer < ActionMailer::Base default from: "johnpaulprince22@gmail.com" # might pass users def sample_email(user) @user = user mail(to: @user.email, subject: '') end end
class Featured < ActiveRecord::Base belongs_to :story validates_presence_of :story_id validates_uniqueness_of :story_id cattr_reader :per_page @@per_page = 10 def month self.created_at.strftime('%B %y') end end