text stringlengths 10 2.61M |
|---|
class RenameAboutUsTypeForUsers < ActiveRecord::Migration
def up
rename_column :users, :about_us_type, :affiliation_list
end
def down
rename_column :users, :affiliation_list, :about_us_type
end
end
|
class ValidationTrackersController < ApplicationController
# GET /validation_trackers
# GET /validation_trackers.json
def index
@validation_trackers = ValidationTracker.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @validation_trackers }
end
end
#... |
# frozen_string_literal: true
# rubocop:todo all
# Copyright (C) 2014-2022 MongoDB Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... |
class ProfileCompCardPhoto < ApplicationRecord
belongs_to :profile_comp_card
belongs_to :profile_photo
#validation
validates_presence_of :profile_photo, :profile_comp_card,
:sequence
end
|
# Iterate through an array
properties = ['object oriented' , 'duck typed' , 'productive' , 'fun']
properties.each {|property| puts "Ruby is #{property}."}
# One quote around a string means the string should be interpreted literally, and two quotes leads to string evaluation
# ----
# Ruby is a pure object-oriented ... |
class EventsController < ChargebeeRails::WebhooksController
# Here we can do things like notifying customer through mail
# about new subscription with the application
def subscription_created
puts event
end
end
|
$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
require 'set'
require 'logger'
module DataMetaDom
# Logger set to WARN, daily rollover and max size 10M
# Feel free to change any of it.
L = Logger.new('dataMetaDom.log', 'daily', 10... |
require 'rails_helper'
RSpec.describe Telefone, type: :model do
describe "validations" do
it { is_expected.to validate_presence_of(:ddd) }
it { is_expected.to validate_presence_of(:numero) }
it { is_expected.to validate_presence_of(:tipo) }
end
describe "associations" do
it{ is_expected.to belo... |
require_relative '../util'
RSpec.describe "Util" do
UBERFLIP_IMAGE_URL = 'https://content.cdntwrk.com/files/aHViPTY2NDg5JmNtZD1pdGVtZWRpdG9yaW1hZ2UmZmlsZW5hbWU9aXRlbWVkaXRvcmltYWdlXzVhZTc2ZDZmMmM5NzQuanBnJnZlcnNpb249MDAwMCZzaWc9NWI4MmRiMjhjMzZlYTYzM2I1ZTBlNjA3ODE3ODE4ZWM%253D'
TEST_ITEMS = [
{
Constants:... |
class Mailer < ActionMailer::Base
default :from => "myagenda.org@gmail.com"
def registration_notification(user)
mail(:to => user.email,
:subject => "Thank you for Registering at MyAgenda.org",
:body => user)
end
end
|
# frozen_string_literal: true
module RbLint
VERSION = '0.0.1'
end
|
require 'rails_helper'
feature "visitors get to home page" do
scenario "prospect user can sign up with email" do
visit root_path
expect(page).to have_text("Welcome to chermeals!")
click_link "Get started"
fill_in_registration_fields
expect(page).to have_content("Weocome! You have signed up succe... |
class CartellaClinicasController < ApplicationController
before_action :set_cartella_clinica, only: [:show, :edit, :update, :destroy]
# GET /cartella_clinicas
# GET /cartella_clinicas.json
def index
@cartella_clinicas = CartellaClinica.all
end
# GET /cartella_clinicas/1
# GET /cartella_clinicas/1.js... |
class Api::V1::UrlsController < ApplicationController
def create
new_url = Url.new(url_params)
if new_url.save
render json: new_url
else
if new_url.errors.messages[:full_link] == ["has already been taken"]
url = Url.find_by(url_params)
render json: url
else
render... |
#!/usr/bin/env ruby
#
require_relative 'lib/CTF'
require 'timeout'
require 'thread/pool'
if __FILE__ == $0
if ARGV.size != 2
puts "#{$0} ctf_id round"
exit
end
round = ARGV[1].to_i
ctf = CTF.new ARGV[0]
ctf.each_team do |team|
begin
Timeout.timeout(5) do
... |
class AddEpisodeIdToCollection < ActiveRecord::Migration
def change
add_column :collections, :episode_id, :integer
end
end
|
class RemoveTableOrderitem < ActiveRecord::Migration
def change
drop_table(:orderitems)
end
end
|
class Question < ActiveRecord::Base
QUESTION_TYPES = {
'True/False' => 1,
'Single Select Question'=> 2,
'Multiple Select Question' => 3,
'Detail Answer' => 4,
'Email Field' => 5,
'Input Field' => 6,
}
before_save :capitalize_title
before_create :set_order
self.per_page = 10
validates... |
namespace :list_pull do
task :email_campaign => :environment do
count_only = %w(Y y).include?(ENV['COUNT_ONLY'])
output_csv = ENV['OUTPUT_CSV']
raise "You must specify OUTPUT_CSV file" if output_csv.blank? && !count_only
# get config
raise "You must specify CONFIG file" if ENV['CONFIG'... |
Rails.application.routes.draw do
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
root 'dog#index'
get 'murphy' => 'dog#murphy'
get 'wylee' => 'dog#wylee'
get '... |
module Yaks
# State monad-ish thing.
#
# Generate a DSL syntax for immutable classes.
#
# @example
#
# # This code
# Form.create(:search)
# .method("POST")
# .action("/search")
#
# # Can be written as
# Builder.new(Form, [:method, :action]).create(:search) do
# method... |
# encoding: utf-8
module Rubocop
module Cop
module Style
# This cop looks for uses of the *for* keyword.
class For < Cop
MSG = 'Prefer *each* over *for*.'
def on_for(node)
convention(node, :keyword)
end
end
end
end
end
|
feature 'homepage' do
scenario 'expect homepage to have header, textbox and submit button' do
visit('/')
expect(page).to have_content "Chitter"
expect(page).to have_content "Sign up"
expect(page).to have_content "Sign in"
expect(page.current_path).to eq '/'
end
feature 'signup' do
scenari... |
require "rails_helper"
RSpec.describe Api::AgenciesController, type: :routing do
describe "routing" do
it "routes to #index" do
expect(get: "/api/agencies").to route_to("api/agencies#index", format: :json)
end
it "routes to #create" do
expect(post: "/api/agencies").to route_to("api/agencies... |
# Integer right triangles
# Problem 39
# If p is the perimeter of a right angle triangle with integral length sides,
# {a,b,c}, there are exactly three solutions for p = 120.
# {20,48,52}, {24,45,51}, {30,40,50}
# For which value of p ≤ 1000, is the number of solutions maximised?
require 'benchmark'
class Euler39
... |
require 'test_helper'
require 'generators/generators_test_helper'
require "generators/fullcalendar-rails/install/install_generator"
class InstallGeneratorTest < Rails::Generators::TestCase
include GeneratorsTestHelper
tests Fullcalendar::Generators::InstallGenerator
def setup
Rails.application.class.stubs(... |
# When done, submit this entire file to the autograder.
# Part 1
def sum arr
arr.inject(0, :+)
end
def max_2_sum arr
arr.max(2).reduce(0,:+)
end
def sum_to_n? arr, n
(0..arr.length-1).any? do |i|
arr[i+1..-1].any? { |x| x + arr[i] ==n }
end
end
# Part 2
def hello(name)
return 'Hello, '+name
end
def... |
require 'digest/sha1'
class User < ActiveRecord::Base
include Authentication
include Authentication::ByPassword
include Authentication::ByCookieToken
validates_presence_of :login
validates_length_of :login, :within => 3..40
validates_uniqueness_of :login
#validates_format_of :log... |
class Node
include Comparable
attr_accessor :left, :right, :data
def initialize(data)
@left = nil
@right = nil
@data = data
end
def <=>(other_node)
@data <=> other_node.data
end
def to_s
return @data
end
end
|
module ApplicationHelper
def sortable(column, title = nil)
title ||= column.titleize
css_class = (column == sort_column) ? "current #{sort_direction}" : nil
direction = (column == sort_column && sort_direction == "asc") ? "desc" : "asc"
link_to title, {:sort => column, :direction => direction,... |
class CreateMitglied < ActiveRecord::Migration
def self.up
create_table(:Mitglied, :primary_key => :mnr) do |t|
# Mitgliedsnummer, PS, FS
t.integer :mnr, :null => false, :uniqueness => true, :limit => 10, :primary => true
# RVDatum
t.date :rvDatum, :default => nil
end
end
def self... |
# frozen_string_literal: true
module Orders
class Create < Actor
input :attributes, type: Hash
output :order, type: Order
def call
user_id = create_or_find_user(attributes)
self.order = Order.create(attributes.except(:user, :user_id).merge(user_id: user_id))
order.save!
end
... |
# TODO: move it to app/controllers/locomotive/concerns
module Locomotive
module Routing
module SiteDispatcher
extend ActiveSupport::Concern
included do
if self.respond_to?(:before_filter)
helper_method :current_site
end
end
protected
def current_site
... |
#!/usr/bin/env ruby
puts "Input your email"
email = gets.chomp
until User.exists?(:email => email)
puts "User does not exist, please try again"
email = gets.chomp
end
user = User.find_by(email: email)
puts ""
puts "What do you want to do?"
puts "0. Create shortened URL"
puts "1. Visit shortened URL"
choice ... |
module DataTransfer
module ClassMethods
def import(file_path, method = 'YAML')
if File.file?(file_path)
obj = if method.casecmp('serialize').zero?
Marshal.load(File.read(file_path))
else
YAML.load(File.read(file_path))
end
end
... |
system "clear"
def get_matrix(q)
puts "Enter size of matrix_#{q}"
print "n = "
n = gets.to_i
print "m = "
m = gets.to_i
repeat = true
i = 0
while repeat && i != n
print "Size of matrix_#{q}: #{n}x#{m}\n"
puts "Enter the elements of matrix_#{q} separated by a space, Enter."
a = []
a[0] = ... |
require 'test_helper'
class WelcomeSlidesControllerTest < ActionController::TestCase
setup do
@welcome_slide = welcome_slides(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:welcome_slides)
end
test "should get new" do
get :new
assert... |
# we have a list of base currencies which need to be refreshed regularly
class Tasks::Cron::RefreshBaseCurrencies
BASE_CURRENCY = 'BTC'.freeze
def initialize
puts "Task initialized."
end
def perform
puts "We ensure the base currencies .."
ensure_base_currencies
ensure_bitcoin
puts "We ref... |
module Faceter
module Nodes
# The composed node that describes a field of tuples in input data
#
# @api private
#
class Field < AbstractMapper::AST::Branch
attribute :key
# Builds a transproc function for the field node from its child nodes
#
# @return [Transproc::Funct... |
class ReferralAttrItem < ActiveRecord::Base
attr_accessible :name, :sort, :referral_attr_category_id, :updated_by
belongs_to :referral_attr_category
scope :for_category, lambda{|category| where("referral_attr_category_id = ?", category)}
end
|
class Picture < ActiveRecord::Base
belongs_to :user
has_attached_file :photo, :styles => { :medium => "300x300>", :thumb => "100x100>" }
def width
geo = Paperclip::Geometry.from_file(photo.to_file(:original))
geo.width
end
def height
geo = Paperclip::Geometry.from_file(photo.to_file(:original))
geo.he... |
FactoryBot.define do
factory :report do
user
association :reportable, factory: :article
description { 'A report description' }
end
end
|
# DB Schema in English
class CreateTeachers < ActiveRecord::Migration
def change
create_table :teachers do |teacher|
teacher.text :email, :hashed_password, :salt, :token_salt
teacher.timestamps null: false
end
end
end
|
require 'spec_helper'
feature User, 'has inventory containing some private datasets:' do
before do
@user = FactoryGirl.create(:user)
given_logged_in_as(@user)
end
scenario 'and sees only public elements in the catalog' do
given_organization_with_opening_plan
private_dataset_attributes = attribut... |
#!/usr/bin/env ruby
require 'yaml'
require 'tempfile'
require 'English'
# Used to compare the output of the `cratus` command across multiple runs
input1 = ARGV[0]
input2 = ARGV[1]
# Find our diff command and break if we don't have one
diff_path = `which diff`.chomp
raise 'Missing diff command in PATH!' unless $CHIL... |
#
# Be sure to run `pod lib lint TestSpecs.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'TestSpecs'... |
require 'test_helper'
class LetterCampaignTest < ActiveSupport::TestCase
test "Total for given day" do
expected = LetterCampaign.find(:all, :conditions => "date(created_at) = '#{ (Date.today - 1.day).to_date.strftime('%Y-%m-%d')}' and name = 'Test Tribe'").count
data = LetterCampaign.tribe_total_on('Test Tribe',... |
# encoding: utf-8
class AdvertisementsController < ApplicationController
skip_before_action :authorize
before_action :set_advertisement, only: [:show, :edit, :update, :destroy]
before_action :correct_advertisement, only: [:edit, :update, :destroy]
def index
buf = Advertisement.all
category_id = p... |
class Admin < ActiveRecord::Base
validates :onid, :presence => true
end
|
namespace :dev do
desc "Create sample data for local development"
task seed: ['db:setup'] do
unless Rails.env.development?
raise "This task can only be run in the development environment"
end
require 'factory_girl_rails'
create_users
end
def create_users
header "Users"
10.ti... |
class Genre < ActiveRecord::Base
has_many :book_genres
has_many :books, through: :book_genres
has_many :authors, through: :books
validates_uniqueness_of :name
def find_genres_books(current_user)
self.books.where(user_id: current_user.id).order(:title)
end
def find_genres_borrowable_books(curren... |
class Book
attr_accessor :pages, :title
@@library_count = 0
def initialize pages = 0, title="N/A"
@pages = pages
@title = title
@@library_count += 1
end
def self.library_count
@@library_count
end
def happy
"There are #{@pages} happy pages in this book"
end
end
|
require('rspec')
require('pry')
require('prime_sifting')
describe('#array_creator') do
it('creates an array of values for any number') do
array = Prime.new()
expect(array.array_creator(3)).to(eq([2,3]))
end
end
describe('prime_times') do
it('removes all multiples of 2 that are greater than 2 from a given... |
require_relative '../test_config'
require_relative "#{SOURCE_ROOT}/system/battle_system"
require_relative "#{SOURCE_ROOT}/component/battle_component"
require_relative "#{SOURCE_ROOT}/component/display_component"
require_relative "#{SOURCE_ROOT}/model/entity"
class BattleSystemTest < Test::Unit::TestCase
def setup
... |
module AccountMutations
MUTATION_TARGET = 'account'.freeze
PARENTS = [].freeze
class Update < Mutations::UpdateMutation
argument :refresh_account, GraphQL::Types::Int, required: false, camelize: false
end
end
|
class RemoveSerialToEquipment < ActiveRecord::Migration[5.2]
def change
remove_column :equipment, :serial, :string
remove_column :equipment, :fixed_assets, :string
end
end
|
require 'rails_helper'
RSpec.describe PostGameHelper, :type => :helper do
describe '#set_winner' do
it 'sets the game winner' do
game = build(:game)
team = build(:team)
expect{set_winner(game, team)}.to change{game.winner}.from(nil).to(team)
end
end
describe '#update_correct_counts' do
it 'incr... |
require 'vizier/argument-decorators/base'
module Vizier
#Consumes several positions with the decorated argument.
# repeating.file_argument :some_files
#
# > do_thing_to files/one.txt files/two.txt files/three.txt
#
#Will collect an array into +some_files+ of validated files.
class Repeating < ArgumentDe... |
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: 'home#index'
#get '/', to: 'home#index', as:'home'
#get '/cards/fav'
#cada rota vai para uma action
#get 'cards/:id', to: 'cards#show'
#get 'cards/', to: 'cards#in... |
# frozen_string_literal: true
require_relative 'afk/configuration'
require_relative 'afk/formatter'
require_relative 'afk/node_collection'
require_relative 'afk/project'
require_relative 'afk/runner'
require_relative 'afk/task'
require_relative 'afk/version'
require_relative 'afk/trello/importer'
require_relative 'afk... |
# frozen_string_literal: true
RSpec.describe HelpScout::Thread do
let(:conversation_id) { ENV.fetch('TEST_CONVERSATION_ID') }
let(:thread_id) { ENV.fetch('TEST_THREAD_ID') }
describe '.get' do
it "returns a #{described_class} given a conversation_id and thread_id" do
thread = described_class.get(conve... |
# ----------
# Question 1
# ----------
# class MyCar
# attr_accessor :speed, :color
# attr_reader :year
# def initialize(y, c, m)
# @year = y
# @color = c
# @model = m
# @speed = 0
# end
# def speed_up(number)
# self.speed += number
# puts "You are now driving at #{speed} mph."
# ... |
class CitiesController < ApplicationController
def index
@cities = City.all.paginate(page: params[:page])
unless params[:q].to_s.empty?
like_query = "%#{params[:q].upcase}%"
@cities = @cities.where("upper(name) like ? ", like_query)
end
end
end
|
Pod::Spec.new do |spec|
spec.name = "TSAVideoCallSDKHB"
spec.version = "0.2.6"
spec.summary = "TSAVideoCall SDK for video conference."
spec.homepage = "https://github.com/smpb05/TSAVideoCallSDKHB"
spec.license = "MIT"
spec.author = { "Smartex" => "nurgul.aisariyeva@sma... |
# frozen_string_literal: true
module GuestyAPI
VERSION = '0.2.3'
end
|
module Localeze
class CustomAttribute < ActiveRecord::Base
establish_connection("localeze_#{RAILS_ENV}")
validates_presence_of :base_record_id, :name
validates_uniqueness_of :name, :scope => :base_record_id
belongs_to :base_record, :class_name => "Localeze::BaseRecord"
end
end |
Rails.application.routes.draw do
resources :presenca_aulas
resources :aulas
resources :matriculas
resources :nota_trabalhos
resources :trabalhos
resources :provas
resources :prova_livros
resources :aluno_livros
resources :livros
resources :professores
resources :cidades
resources :estados
reso... |
require 'test_helper'
class ActiveRecordTest < ActiveSupport::TestCase
def setup
Geocoder::Configuration.lookup = :google
Geocoder::Configuration.cache = nil
end
test "associations" do
assert_equal [venues(:beacon)], colors(:red).venues
end
test "use of includes doesn't raise error" do
ass... |
module CVE
class Filter
def initialize(history_size=100)
@history = []
@history_size = history_size
end
attr_accessor :history, :history_size
def filter(contents)
return true unless contents.is_a?(Vulnerability)
return true if cve_exists?(contents.identifier)
history_c... |
class Appointment < ApplicationRecord
belongs_to :doctor
belongs_to :patient
validates_presence_of :appointment_date, :appointment_time
end
|
require 'rails_helper'
RSpec.describe Request, type: :model do
subject(:request) { build(:request) }
it 'has a valid factory' do
expect(request).to be_valid
end
end
|
require 'rails_helper'
describe Subject do
it { should belong_to(:topic) }
it { should belong_to(:user) }
it { should validate_presence_of(:title) }
it { should validate_presence_of(:user_id) }
it { should validate_presence_of(:topic_id) }
it { should have_many(:posts) }
end |
class Scrabble
attr_reader :word
attr_reader :score
def initialize(word)
@word = word
@score = 0
end
def score
if @word == '' || @word == '\n' || @word == nil
return 0
# elsif @word == 'a'
# return 1
# elsif @word == 'f'
# return 4
else
@word = @word.do... |
require_relative 'app_spec_helper'
describe "Validation" do
describe "Post Trailing White Space Parameters" do
describe "Post param with pre white space" do
venue = standard_venue_json
venue["name"] = add_pre_white_space(venue["name"])
post('/venues/new', venue.to_json, standard_header)
... |
class StructureCloneService < BaseServicer
attr_accessor :params,
:audit_structure
attr_reader :cloned_structure
def execute!
@params ||= {}
clone_structure
clone_physical_structure
clone_field_values
clone_sample_groups
clone_substructures
end
private
def clone_f... |
module CoinPrice
module PTAX
class API
ENDPOINT = 'https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1'
ENDPOINT_COTACAO_DOLAR_DIA = "#{ENDPOINT}/odata/CotacaoDolarDia(dataCotacao=@dataCotacao)"
class << self
# Docs: https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/documentac... |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'linked_bus/version'
Gem::Specification.new do |spec|
spec.name = "linked_bus"
spec.version = LinkedBus::VERSION
spec.authors = ['Pedro Cunha', 'Thiago Dantas']
spec.e... |
class Proselint < Formula
include Language::Python::Virtualenv
desc "Linter for prose"
homepage "http://proselint.com"
url "https://files.pythonhosted.org/packages/e9/fc/acd766ee050c8a8a27439fcb37a7042d9fc44bf840b48ebb32a5546a9db8/proselint-0.12.0.tar.gz"
sha256 "2a98d9c14382d94ed9122a6c0b0657a814cd5c892c77d... |
class RacesController < ApplicationController
before_action :get_race, only: [:update, :edit, :show, :destroy]
before_action :get_game
before_action :get_races
def index
@races = @game.races
end
def new
@race = @game.races.new
render "form"
end
def create
@race = @game.races.new(race_... |
class Kprop < ActiveRecord::Base
belongs_to :kunstvoorwerp
belongs_to :kunstproperty
end
|
class AdvicesController < ApplicationController
layout 'sidenav'
before_action :team_session
before_action :set_advice, only: [:show, :edit, :update, :destroy]
# GET /advices
# GET /advices.json
def index
return if @team.blank?
Vortrics.config[:advices].each_key do |key|
@team.advices.create_... |
class ReviewsController < ApplicationController
def create
review = Review.new(review_params)
review.product = Product.find_by(id: params[:id])
if @logged_in_merchant
merchant_products = Product.all.where(merchant_id:@logged_in_merchant.id)
products = merchant_products.map { |p| p.id }
... |
class AddGuestToShopquikTodoList < ActiveRecord::Migration
def change
add_reference :shopquik_todo_lists, :guest, index: true, foreign_key: true
end
end
|
require File.expand_path '../test_helper.rb', __FILE__
class TestApp < MiniTest::Test
def setup
Resource.create(name: 'Resource #1')
end
def test_index
resources = Resource.select('id', 'name')
get '/'
assert last_response.ok?
assert_equal resources.to_json, last_response.body
end
def ... |
require 'rails_helper'
RSpec.describe "service_attribute_values/new", type: :view do
before(:each) do
assign(:service_attribute_value, ServiceAttributeValue.new(
:service_attribute_id => 1,
:key => "MyString",
:name => "MyString"
))
end
it "renders new service_attribute_value form" do
... |
require 'spec_helper'
describe "Static Pages" do
let(:base_title) { "Ruby on Rails Tutorial Sample App" }
subject {page}
shared_examples_for "all static pages" do
it { is_expected.to have_selector('h1', text: heading) }
it { is_expected.to have_title(full_title(page_title)) }
end
describe "Home p... |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
#!/usr/bin/ruby
# A empty array
a = []
puts a
puts a.length
# Find max element
b = [1, 3, 7, 9, 5]
puts b.max
# Index
puts "I'd like find a even number in #{b}"
if not b.index(4)
puts "as expected, not find the even number"
end
# Directly modify the array
b.sort!
puts b
# Join
a=["hello", "world", "my", "frien... |
class Item < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
has_many :item_images, dependent: :destroy
belongs_to :category, optional: true
belongs_to_active_hash :prefecture
belongs_to_active_hash :condition
belongs_to_active_hash :postage
belongs_to_active_hash :prepare
belo... |
require 'nokogiri'
require_relative 'database'
class Book
attr_reader :row
attr_accessor :max
def initialize(row)
@row = row
end
def title_cell
@title_cell ||= row.css('td.g-title')
end
def title_link
@title_link ||= title_cell.css('h5')
end
def url
'https://www.amazon.com' + tit... |
class UsersController < ApplicationController
skip_before_action :authenticate
def index
@users = User.all
@user = user.find(params[:id])||current_user
end
def show
@user = User.find(params[:id])
@post = @user.posts
end
def signup
end
def signup!
user = User.new(
username: ... |
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :users, only: [:new, :create]
resources :sessions, only: [:new, :create] do
delete :destroy, on: :collection
end
resources :homes, only: [:index]
get '/about' ... |
class City < ActiveRecord::Base
has_many :restaurants
include UpdateOrCreate
end
|
module NcsNavigator::Authorization::StaffPortal
class Client
attr_reader :connection
def initialize(url, options, &block)
@connection = NcsNavigator::Authorization::StaffPortal::Connection.new(url, options, &block)
end
end
end |
describe "A user" do
it "requires a name" do
# Arrange
user = User.new(name: "")
user.valid? # populates errors
# Assert
expect(user.errors[:name].any?).to eq(true)
end
it "requires an email" do
user = User.new(email: "")
user.valid?
expect(user.errors[:email].any?).to eq(true... |
require 'rails_helper'
RSpec.describe "residents/index", type: :view do
before(:each) do
assign(:residents, [
Resident.create!(
:name => "Name",
:first_name => "First Name",
:last_name => "Last Name",
:phone => "Phone",
:email => "Email",
:starting_balance =>... |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
class Review < ApplicationRecord
belongs_to :recipient, :class_name => 'User'
belongs_to :helper, :class_name => 'User'
belongs_to :favour
validates :rating, presence: true
end
|
require 'unicode_utils/downcase'
require 'nokogiri'
require 'open-uri'
class Weather
def initialize(city)
@city = UnicodeUtils.downcase(city)
@uri = "https://pogoda.mail.ru/prognoz/#{@city.gsub(/-/, '_')}"
@encoded = URI.encode(@uri)
@url = URI.parse(@encoded)
begin
@doc = Nokogiri::HTML(... |
# == Schema Information
#
# Table name: employees
#
# id :bigint not null, primary key
# active :boolean default(TRUE)
# name :string
# created_at :datetime not null
# updated_at :datetime not null
# user_id :integer
#
# Indexes
#
# index_employees_on_activ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.