text
stringlengths
10
2.61M
class Picture < ApplicationRecord belongs_to :gallery, foreign_key: :gid, primary_key: :gid end
Rails.application.routes.draw do get '/' => 'posts#index', as: :index resources :posts do resources :comments resources :favourites, only: [:create, :destroy] end resources :favourites, only: [:index] resources :users, only: [:new, :create, :edit, :update] do collection do get :change_p...
# Rotation Part 2 =begin (Understand the Problem) Problem: Write a method that can rotate the last n digits of a number Inputs: Integer Outputs: Integer Questions: 1. Explicit Rules: 1. Note that rotating just 1 digit results in the original number being returned 2. You may assume that n is ...
class PushServices::GoalNotifier def initialize(current_user, goal) @current_user = current_user @goal = goal end def notify_challenge_to(user) notifier.push( message: challenge_message, tag: user.airship_tag, extra_data: { event_type: PushServices::Notifier::EVENT_TYPES[...
require 'spec_helper' bool_options = [true, false] describe 'secure_linux_cis::debian9::cis_5_2_15' do on_supported_os.each do |os, os_facts| bool_options.each do |option| context "on #{os} with default key exchange algorithms" do let(:facts) { os_facts } let(:params) do { 'enfor...
# frozen_string_literal: true # EBWiki Users controller class UsersController < ApplicationController around_action :skip_bullet, only: :show def show @user = User.find(params[:id]) @cases = @user.all_following end def edit @user = User.find(params[:id]) authorize @user end def update ...
Gem::Specification.new do |s| s.name = 'jently' s.version = '1.0.2' s.date = '2012-09-11' s.summary = "A Ruby application that allows for communication between the Jenkins CI and Github." s.description = "A Ruby application that allows for communication between the Jenkins CI and Github....
RSpec.describe PartnerMailerJob, type: :job do describe "conditionally sending the emails" do let(:organization) { create :organization } let(:mailer_subject) { 'PartnerMailerJob subject' } let(:distribution) { create :distribution } let(:past_distribution) { create(:distribution, issued_at: Time.zon...
# frozen_string_literal: true # This migration comes from alchemy (originally 20200504210159) class RemoveSiteIdFromNodes < ActiveRecord::Migration[5.2] def up remove_foreign_key :alchemy_nodes, :alchemy_sites remove_index :alchemy_nodes, :site_id remove_column :alchemy_nodes, :site_id, :integer, null: fa...
require 'spec_helper' require 'pry' describe ModelView do let(:dummy_class) { Class.new { extend ModelView } } let(:root_scope) { :__root__ } context "root scope" do describe :field do context "without a block" do it "adds the field to the root scope" do dummy_class.field :a_field ...
module Fauve module Scheme # Representation of a colour as part of a wider scheme. # Holds a raw colour and a colour with filters applied. # Requires Fauve::Scheme::ColourMap, Fauve::Scheme::Section # and Fauve::Scheme::Reference class Colour @@candidates = [] attr_reader :filters,...
class RenameColumnOccupationToOccupationId < ActiveRecord::Migration def self.up rename_column :contacts, :occupation, :occupation_id end def self.down rename_column :contacts, :occupation_id, :occupation end end
class CreateExerciseMuscles < ActiveRecord::Migration def self.up create_table :exercise_muscles do |t| t.references :exercise t.references :muscle t.timestamps end end def self.down drop_table :exercise_muscles end end
class ImageGroup < ActiveRecord:: validates :name, presence: true validates :product_id, presence: true belongs_to :product has_many :variants has_many :images, -> {order(:position)}, as: :imageable, dependent: :destroy after_save :expire_cache ...
require 'open-uri' require 'pry' require "nokogiri" class Scraper @@scraped_students = [] attr_accessor :scraped_student def self.scrape_index_page(index_url) html = File.read(index_url) index_page = Nokogiri::HTML(html) index_page.css("div.student-card").each do |student| @@scraped_students <<...
class RemoveIdentityFieldInMembers < ActiveRecord::Migration def self.up remove_column :members, :identity end def self.down end end
require_relative "./board.rb" require 'yaml' class Game def initialize n_or_l, filename = self.new_or_load? if n_or_l == "n" system "clear" difficulty = self.difficulty? @board = Board.new(difficulty) self.run elsif n_or_l == "...
class User include DataMapper::Resource include BCrypt include Gravatarify::Helper property :id, Serial, :key => true property :forename , String property :familyname , String, :lazy => [ :show ] property :username, String, :length => 3..50, :required => true, :unique => true, :lazy => [ :show ] proper...
class SearchesController < ApplicationController def search @routes = Route.where('origin iLike? OR destination iLike?', "%#{params[:from]}%", "%#{params[:destination]}%").order(created_at: :desc) end end
# frozen_string_literal: true RSpec.describe 'Mod Request', type: :request do include_context 'with branch location' include_context 'with user token' include_context 'with json response' include_context 'with event' let(:mod_section) { build(:mod_section, event: event) } before do event.update!(mod_...
class Event < ApplicationRecord belongs_to :host, class_name: 'User' has_many :invitations, dependent: :destroy has_many :attendees,->{where invitations:{accepted:true}}, class_name: 'User', :through=> :invitations validates :title, presence: true, length: {maximum: 50} validates :description, presence: true val...
# frozen_string_literal: true require 'encase' module Jiji::Model::Notification class ActionDispatcher include Encase include Jiji::Errors needs :rmt needs :backtest_repository def dispatch(backtest_id, agent_id, action) resolve_target(backtest_id).process.post_exec do |context, _queue|...
require "application_system_test_case" class AdministradoresTest < ApplicationSystemTestCase setup do @administrador = administradores(:one) end test "visiting the index" do visit administradores_url assert_selector "h1", text: "Administradores" end test "creating a Administrador" do visit ...
# This file sets up the various include paths and whatnot that would have been set up # for us by Rails if this were a Rails plugin. require File.expand_path("../lib/auth", File.dirname(__FILE__)) base_path = File.expand_path(File.join(File.dirname(__FILE__), '..')) def add_to_load_path(path, load_once = false) loa...
require 'rspec' require 'utils' describe Utils do it("Contains utilities functions for cli and service") {} before(:all) do @path = 'myfile.list' @contents = "one a\ntwo b\nthree c\n" @file_lines = ["one a\n", "two b\n", "three c\n"] @item_key = 'four' @item_value = 'd' @existing_key = '...
require_relative 'shasum.rb' require_relative 'platform.rb' require_relative 'formula.rb' class HostBase < Formula include Properties include SingleVersion namespace :host BIN_LIST_FILE = 'list' DEV_LIST_FILE = 'list-dev' def initialize(path) super path # todo: handle platform dependant instal...
class ExepertWritersController < ApplicationController before_action :set_exepert_writer, only: [:show, :edit, :update, :destroy] # GET /exepert_writers # GET /exepert_writers.json def index @exepert_writers = ExeprtWriter.all end # GET /exepert_writers/1 # GET /exepert_writers/1.json def show e...
class Model::Domain::Cta attr_accessor :title attr_accessor :url attr_accessor :strapline attr_accessor :header attr_accessor :supporting_text def initialize @title = "CTA title #{Time.current.strftime("%T")} #{String.random(4)}" @url = "http://www.google.co.uk/" @strapline = "CTA Strapline #{T...
Rails.application.routes.draw do #Rotas para as páginas da presidências get 'directions/presidencia', to: "directions#presidencia", as: :presidencia get 'directions/gp', to: "directions#gp", as: :gp get 'directions/financeiro', to: "directions#financeiro", as: :financeiro get 'directions/projetos', to: ...
# frozen_string_literal: true module Api::V1::VideoCategories IndexSchema = Dry::Validation.Params(BaseSchema) do optional(:sort).filled(:str?) optional(:filter).schema do optional(:name).filled(:str?) end optional(:page).schema do required(:number).filled(:int?, gt?: 0) required(...
class Pizza attr_reader :description def initialize raise NotImplementedError, "Abstract class: Must be overriden in the subclass" end def get_description description end def cost raise NotImplementedError, "Must be overriden in the subclass" end end class ThinCrustPizza < Pizza def init...
class Printer attr_reader :count def initialize @count=0 end def print(caller) puts "#{caller}: #{@count}" @count+=1 end end p1=Printer.new #t2= Thread.new {100.times {|i| puts "#{i} "}} #t1= Thread.new {100.times {|i| puts i}} t2= Thread.new {100.times {p1.print("t2")}} t1= Thread.new {100...
require 'starfish/channel' require 'starfish/build' require 'starfish/pull_request' require 'starfish/not_found' require 'starfish/automatic_release_event' module Starfish class Pipeline attr_reader :id, :name, :project, :branch, :builds, :channels, :pull_requests attr_reader :notification_targets def i...
require 'test/unit' require 'rubygems' require "#{File.dirname(__FILE__)}/../init" class SexyTempPasswordsTest < Test::Unit::TestCase def test_sexy_temp_password 10.times do random_pass = SexyTempPassword.generate length = random_pass.size word_part, num_part = random_pass[0..(length-5)], ran...
#!/usr/bin/ruby # frozen_string_literal: true require 'fileutils' require 'xcodeproj' require 'net/http' require 'json' require_relative 'command/command_factory' require_relative 'models/panthage_cmdline' raise "fatal: wrong args usage #{ARGV}" unless ARGV.length >= 3 def show_help_info puts "********** help scr...
class Api::ShopsController < Api::BaseController before_action :set_shop skip_before_action :authenticate_user! def show location = @shop.try(:location).try(:delivery_address_without_phone) hash = @shop.as_json(only: [ :name, :title, :id ], methods: [:avatar_url]) hash['location'] = location ren...
class Api::AttendancesController < ApplicationController before_action :set_attendance, only: [:destroy] respond_to :json def create @attendance = Attendance.find_or_initialize_by(event_id: params[:event_id], user_id: params[:user_id]) if @attendance.new_record? if @attendance.save render j...
require 'maws/command' class VolumesCommand < Command def create_ebs_from_descriptions specified_roles = @maws.specified_roles specified_zones = @maws.specified_zones connection.ebs_descriptions.map { |description| instance = description.create_instance(self, @config) next unless instance.na...
class User < ActiveRecord::Base has_many :my_coffees has_many :coffees, through: :my_coffees def coffee_names self.coffees.map do |coffee| coffee.name end end end
class Api::V1::BatchesController < Api::V1::BaseApiController def index facilities = params[:facility_id].split(',').map { |x| x.to_bson_id } # batches = Cultivation::Batch.all.order(c_at: :desc) # phases = extract_phases(batches) exclude_tasks = params[:exclude_tasks] == 'true' || false # options...
######################################### # This class provided the methods to manage to execute FASTQC ######################################### class Fastqc def initialize(files_array,cores,output_path) @files_array = files_array @output_path = output_path #make output path Dir.mkdir(output_path) if !...
class Inventory < ActiveRecord::Base belongs_to :player belongs_to :item validate :not_already_purchased, on: :create validate :has_enough_gold, on: :create def not_already_purchased errors.add(:item_id, "Item already bought") if player.inventories.any? { |inv| inv.item_id == item_id } end def has_...
class MessageFinder def initialize(verbose: false, **kwargs) @verbose = verbose @fps = (kwargs[:fps] || 10).to_i @iter = (kwargs[:iter] || 0).to_i @max_iter = (kwargs[:max_iter] || 1_000_000).to_i @pixel = kwargs[:pixel] || "#" @space = kwargs[:space] || " " @zoom = @prev_zoom = Float::INF...
unless PluginRoutes.static_system_info['user_model'].present? module CamaleonCms class User < CamaleonRecord include CamaleonCms::UserMethods self.table_name = PluginRoutes.static_system_info['cama_users_db_table'] || "#{PluginRoutes.static_system_info['db_prefix']}users" default_scope { order...
require 'spec_helper' describe Solution do before(:each) do @user = Factory(:user) @problem = Factory(:problem, :user => @user) @attr = { :name => "Example Problem", :comment => "Example comments" } end it "should create a new instance given valid attributes" do @problem.solutio...
class ChangeDefaultForMovies < ActiveRecord::Migration[5.2] def change change_column :movies, :available_inventory, :integer, default: :inventory end end
module BookingDataSystem # # Booking boat information # module BookingCrew def self.included(model) if model.respond_to?(:property) model.property :include_crew, DataMapper::Property::Boolean, :default => false end end end end
require 'rails_helper' module ApplicationHelper def view_test(controller, currency, number, time, foreign_currency) visit "/#{controller}/#{number}_#{time}" expect(page).to have_current_path("/#{controller}/#{number}_#{time}") expect(page).to have_css("#chart-1") expect(page).to h...
require 'set' if defined?(Rails) && defined?(Rails::Engine) require 'binflip_rails' end class FauxRedis def smembers(*_); []; end def sadd(*_); true; end def srem(*_); true; end def del(*_); 0; end end class Binflip @rollout = false def initialize(rollout=nil) if rollout && rollout.is_a?(Rollout) ...
# encoding: utf-8 require 'minitest/autorun' $LOAD_PATH.unshift 'lib/' require 'xi/dip' class DetectorTest < Minitest::Unit::TestCase def setup @img_file = File.join('data', 'car.jpg') options = %w[ pixel_value pixel_distance region-4x4_value region-64x64_histogram image_hi...
class AssetLibrary module Compiler class Base def initialize(config) @config = config || {} @asset_modules = [] end attr_reader :config, :asset_modules def add_asset_module(asset_module) @asset_modules << asset_module end def write_all_caches(format =...
class AddPhotoToWorkers < ActiveRecord::Migration def change add_attachment :workers, :photo end end
class Emv < Formula desc "EMV tooling" homepage "https://github.com/caiotavares/emv" url "https://github.com/caiotavares/emv/releases/download/v0.1.0/emv-0.1.0-x86_64-apple-darwin.tar.gz" sha256 "ffbd5c5f27f707e7aa62b6b67c3e8f69d78c597577c63a3b93d524e94d0c333f" license "MIT" def install bin.install "em...
# source: https://launchschool.com/exercises/780205f1 class SumOfMultiples def self.to(end_num, divisors = [3, 5]) # default devisor arg, can be overwritten (1..(end_num - 1)).select do |el| divisors.any? { |divisor| (el % divisor).zero? } end.sum end def initialize(*divisors) @divisors = divi...
# This file contains the definitions of the interpreter and type # analyzer. require_relative 'parser' require_relative 'transform' require_relative 'environment' # This utility method is used by both the interpreter and the type # analyzer. It takes a string containing a Trump program and returns # an array of nodes...
# == Schema Information # # Table name: yh_articles # # id :bigint(8) not null, primary key # action :string # service_type :string # content_id :string # date :date # time :string # urgency :string # category :string # class_code :...
class AddColunmFromArticleDefaulValue < ActiveRecord::Migration def change change_column_default :articles, :published, false change_column_default :articles, :archived, false end end
class Product < ApplicationRecord has_many :product_rebates has_many :rebates, through: :product_rebates end
require File.expand_path(File.join(File.dirname(__FILE__), 'spec_helper')) describe "document with metas", :shared => true do it { @doc[:uuid].should_not be_nil } it { @doc[:metas].should be_kind_of(Array) } it { @doc[:metas].should_not be_empty } it "for each meta should respond positively to kind_of?, is_...
Pod::Spec.new do |s| s.name = "FaceKit" s.version = "2.2.1" s.summary = "Library to generate a 3D avatar from one single front face photo." s.description = <<-DESC FaceKit-Swift is the core technology to generate the a 3D avatar from one single front face photo. The m...
require 'spec_helper' require './lib/services/word_counter' RSpec.describe WordCounter do let(:test_string) { "one two Two dos Dos three three Three" } let(:expected_result) { {"three" => 3, "dos" => 2, "two" => 2, "one" => 1} } let(:result) { described_class.execute(test_string) } describe "#word_count" do ...
class AddDeliveryToOrders < ActiveRecord::Migration def change add_column :orders, :delivery, :float add_column :orders, :subtotal, :float end end
class User < ApplicationRecord has_many :comments, :dependent => :destroy validates :username, :email, presence: true validates :username, :email, uniqueness: true end
class BugGame YES = ["Y", "y", "Yes", "YES"] NO = ["N", "n", "No", "NO"] YOU = { body: 0, neck: 0, head: 0, antennaes: 0, legs: 0, arms: 0, name: "YOU" } I = { body: 0, neck: 0, head: 0, antennaes: 0, legs: 0, arms: 0, name: "I" } def initialize puts "The Game Bug" puts "I HOPE YOU ENJOY THIS GAME...
require 'rails_helper' RSpec.describe ApplicationHelper, type: :helper do describe '.class_for' do subject { helper.class_for(key) } let(:key) { 'key' } context 'current tab' do before do assign(:current_tab, key) end it { is_expected.to eq 'active' } end context 'ot...
module Moon module DataModel # Utility module for formatting debug context information module MessageFormat # Formats an error message to add more contextual info # # @param [String] msg # @param [Hash<Symbol, Object>] ctx # @option ctx [Symbol] :key # @option ctx [String] ...
require 'rspec' require 'definition' require 'word' require 'pry' describe '#Definition' do before(:each) do Word.clear() Definition.clear() @word = Word.new("narky", nil) @word.save() end describe('#==') do it("is the same definition if it has the same attributes as another definition") do ...
FactoryGirl.define do sequence(:code) { |n| "Code #{n}" } factory :ncr_organization, class: Ncr::Organization do code name "Test Organization" factory :ool_organization do code Ncr::Organization::OOL_CODES.first end factory :whsc_organization do code Ncr::Organization::WHSC_CODE ...
# conversions.rb # Chapter 5 Mixing it Up - starts on page 23 # 5.1 conversions # To get the STRING version of an object, # we simply write .to_s after it: var1 = 2 var2 = '5' #this below will turn 2 into a string, and hold two strings together puts var1.to_s + var2 #25 # .to_i gives INTEGER version of an object #...
class BoatOptionType < Configurator has_many :configurator_entities, dependent: :delete_all has_many :selected_options, dependent: :delete_all has_many :boat_types, through: :configurator_entities has_many :boat_for_sales, through: :selected_options has_many :boat_type_modifications, dependent: :destroy ...
require 'spec_helper' require 'erb' include ERB::Util describe Api::V1::ApiInfoController do before :all do # create access token @token = ApiKey.create!.access_token end describe "GET route" do it "should retrun status 200" do get info_path, {}, { "Accept" => "application/json", :auth...
class AddRankToAnchor < ActiveRecord::Migration def change add_column :anchors, :rank, :string, default: "青铜" end end
class CreateVolunteers < ActiveRecord::Migration def change create_table :volunteers do |t| t.string :first_name t.string :last_name t.integer :age t.integer :responsibility_id t.string :phone t.string :email t.integer :congregation_id t.integer :service_time_id ...
require('rspec') require('triangle') describe(Triangle) do describe('#is_triangle') do it('Returns "equilateral" for 3 equal side inputs') do test_triangle = Triangle.new(10,10,10) expect(test_triangle.is_triangle()).to(eq('Equilateral')) end it('Returns "isosceles" for 2 equal side inputs') ...
class GuestsController < ApplicationController #grabs guest_id before_action :set_guest, only: [:show, :edit, :update] #Diplays individual guest information def show #creates guest address @address = "#{@guest.address}\n#{@guest.city} #{@guest.state} #{@guest.zip}\n" @image = "guests/#{@g...
# encoding: utf-8 $: << 'RspecTests/Generated/byte' require 'generated/body_byte' module ByteModule describe ByteModule::Byte do before(:all) do @base_url = ENV['StubServerURI'] dummyToken = 'dummy12321343423' @credentials = MsRest::TokenCredentials.new(dummyToken) cli...
# -*- mode: ruby -*- # vi: set ft=ruby : # Requires the following plugin install to be run first, as well as everything in the readme. # vagrant plugin install vagrant-host-shell # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" options = {} options[:...
# scope.rb a = 5 # variable is initialized in the outer scope 3.times do |n| # method invocation with a block a = 3 # is a accessible here, in an inner scope? end puts a # => 3 because a has been reassigned within the block. # Also note that had the block initialized `a` instead of `n` the...
RACK_ENV = 'test'.freeze unless defined?(RACK_ENV) require File.expand_path(File.dirname(__FILE__) + '/../config/boot') Dir[File.expand_path(File.dirname(__FILE__) + '/../app/helpers/**/*.rb')].each(&method(:require)) require 'simplecov' SimpleCov.start do root(File.join(File.dirname(__FILE__), '..')) coverage_d...
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'full_name', type: :request do include SchemaMatchers let(:token) { 'fa0f28d6-224a-4015-a3b0-81e77de269f2' } let(:auth_header) { { 'Authorization' => "Token token=#{token}" } } let(:user) { build(:user_with_suffix, :loa3) } before do ...
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.box = "ubuntu/trusty64" config.ssh.insert_key = false config.vm.provider "virtualbox" do |vbox| vbox.name = "drupal" vbox.memory = 1024 vbox.cpus = 2 vbox.customize ["modifyvm", :id, "--natdnshostresolver1", "on"...
module Veda module Enquiry module Types class AuthorizedAgentConsumerPlusCommercial def fetch(new_details = {}) generic_request_object(generate_unique_transaction_reference_number) do |bca| bca.product :name => "authorised-agent-consumer-plus-commercial-enquiry", :summary => '...
require 'test_helper' class WelcomesControllerTest < ActionDispatch::IntegrationTest setup do @welcome = welcomes(:one) end test "should get index" do get welcomes_url, as: :json assert_response :success end test "should create welcome" do assert_difference('Welcome.count') do post we...
#!/usr/bin/env ruby # This script simply strips all RTP headers off of a raw Wireshark UDP dump # of the TS-890 audio stream. It assumed you've enabled the high-quality # stream, and have dumped the data to `input.bin` # # You can then load `output.bin` into an audio tool like Audacity file = "input.bin" outfile = "o...
require 'rails_helper' RSpec.describe BusinessHour, type: :model do context'validation tests'do before(:each) do shop = create(:shop) business_hour = create(:business_hour) end it 'ensures business hour day presence' do business_hour = build(:business_hour, day:nil) expect(bus...
class SqlAnalyzer def initialize @strategy = FactoryGirl.strategy_by_name(:build).new end delegate :association, to: :@strategy def result(evaluation) record = @strategy.result(evaluation) obj_associations(record).unshift(record).map { |obj| "#{obj.class.arel_table.create_insert.tap { |im| ...
require_relative 'base_client' require_relative 'skype_client' require_relative 'growlnotify_client' class MultiClient < BaseClient def initialize(config) super(config) @clients = [SkypeClient.new(config), GrowlnotifyClient.new(config)] end def send_message(message, title="") @clients.each{ |client|...
class CreatePlans < ActiveRecord::Migration[5.1] def change create_table :plans do |t| t.string :name t.monetize :amount, null: true t.string :stripe_id, null: false t.boolean :live, null: false t.string :billing_cycle, null: false t.integer :trial_period_days t.timesta...
FactoryBot.define do factory :category do name {"Tシャツ/カットソー(半袖/袖なし)"} ancestry {"1/2"} end end
require 'spec_helper' describe '#Game' do before(:each) do @franchise = Franchise.new({:name => "Halo", :id => nil}) @franchise.save() end describe('#==') do it("is the same game if it has the same attributes as another game") do game = Game.new({:name => "Naima", :franchise_id => @franchise....
#Override the creation of the top-right utility_nav bar (name & logout link) class CustomUtilityNav < ActiveAdmin::Component def build(namespace) super(:id => "utility_nav", :class => "header-item") @namespace = namespace if current_active_admin_user? build_current_user build_logout_link ...
class CreateAttachments < ActiveRecord::Migration def change create_table :attachments do |t| t.references :message t.timestamps end end def self.up change_table :attachments do |t| t.has_attached_file :file end end def self.down drop_attached_file :attachments, :file ...
# frozen_string_literal: true require_dependency 'easy_monitor/application_controller' #:nodoc module EasyMonitor class HealthChecksController < ApplicationController protect_from_forgery # heartbeat of the application def alive render json: { message: t('alive') }, status: 200 end def a...
require 'logger' module Chat module Logging LOGGER = Logger.new(STDOUT) private def info(*args) log(:info, *args) end def debug(*args) log(:debug, *args) end def warn(*args) log(:warn, *args) end def error(*args) log(:error) end def log(type, ...
# frozen_string_literal: true ActiveAdmin.register Location do menu priority: 2 config.batch_actions = true filter :city filter :state filter :country filter :created_at filter :location, multiple: true permit_params :city,:state,:country,:lat,:lat, :radius, :status index do selectable_colu...
class Conta < ActiveRecord::Base belongs_to :correntista has_many :saque has_many :deposito, foreign_key: "conta_destino_id" before_destroy :inativate before_create :corrigeValor # after_validation :corrigeVa/lor # validates_numericality_of :saldoProvisorio, message: ("Deve ser número ou o valor ou 0") u...
class Article < ApplicationRecord has_one_attached:image validates :title, presence: true validates :description, presence: true validates :body, presence: true validates :author, presence: true validates :category, presence: true validates :views, presence: true def previ...
ActiveRecord::Base.logger = $logger ActiveRecord::Migration.verbose = ENV["VERBOSE"] adapter = ENV["ADAPTER"] || "sqlite" case adapter when "sqlite" ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:" when "postgresql" ActiveRecord::Base.establish_connection adapter: "postgresql", data...
class Cat < ActiveRecord::Base COLORS = ['blue', 'green'] validates :birth_date, :color, :name, :sex, :user_id, presence: true validates :color, inclusion: { in: COLORS } validates :sex, inclusion: { in: ['M', 'F'] } belongs_to :owner, class_name: "User", foreign_key: :user_id, inverse_of: :cats...
class Share < ApplicationRecord has_one :location has_and_belongs_to_many :users end