Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder

EVGA Longoria posted:

I have A ranks there, if you actually care about that.

What does this mean?

Adbot
ADBOT LOVES YOU

necrotic
Aug 2, 2005
I owe my brother big time for this!

MALE SHOEGAZE posted:

What does this mean?

CodeClimate grades your code from F to A based on some heuristics. With an A being the "best".

EVGA Longoria
Dec 25, 2005

Let's go exploring!

MALE SHOEGAZE posted:

What does this mean?

CodeClimate grades your code quality based on "code smells" - i.e. repeated code, complex methods, lots of parameters, things like that. None of it is hard and fast rules to code quality.

It's kind of fun to look at, and it helps identify some good refactor points. That's about it.

DSLs tend to get poo poo on by CodeClimate because they involve a lot of code outside of methods, That means Sinatra usually has low grades.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

kayakyakr posted:

As an extension of this conversation, I need to create a bearer-type token for dumb API access. The scripts that will use this are generally dumb, scheduled curl scripts so that oauth-style challenge/expiring tokens are not an option. I don't want to store the key on the DB as it would be an unhashed password. I can't hash it and store it because I need to be able to re-display the key through the interface.

My current plan was to make a string of id:hashed_password, encrypt it with my secret key, then display. It has the benefit of invalidating when they change their password. It has the downside of providing a single point of security failure where, if the secret key is compromised, an attacker can decrypt and gain a hashed password.

Any suggestions or thoughts on the drawbacks of my proposed solution?

When I have to do this, I generate two random strings of a fixed length: token-key and secret. Store the token-key in a column with a unique constraint, and the bcrypt of the secret. If you just want the client to see the simplicity of a single string, concatenate them. To look up the user from the token, split it, find based on key, and match the bcrypt(secret). Don't expose primary keys or anything like that to users, they'll do something fucky.

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder

EVGA Longoria posted:

CodeClimate grades your code quality based on "code smells" - i.e. repeated code, complex methods, lots of parameters, things like that. None of it is hard and fast rules to code quality.

It's kind of fun to look at, and it helps identify some good refactor points. That's about it.

DSLs tend to get poo poo on by CodeClimate because they involve a lot of code outside of methods, That means Sinatra usually has low grades.

You should really never be writing a DSL unless you're writing a gem or library intended for consumption by unknown entities. You have to generalize a solution beyond what is practical or necessary for your own uses, and the work involved in writing your stupid declarative methods is not worth it when all you need to be doing is writing an interface and saying 'hey if you want to use this library, your classes need to provide these interfaces'

EVGA Longoria
Dec 25, 2005

Let's go exploring!

MALE SHOEGAZE posted:

You should really never be writing a DSL unless you're writing a gem or library intended for consumption by unknown entities. You have to generalize a solution beyond what is practical or necessary for your own uses, and the work involved in writing your stupid declarative methods is not worth it when all you need to be doing is writing an interface and saying 'hey if you want to use this library, your classes need to provide these interfaces'

Not talking about writing a DSL. Talking about using a DSL (Sinatra) getting penalized by CodeClimate.

Buckhead
Aug 12, 2005

___ days until the 2010 trade deadline :(
I need to process a string word by word and see if certain words match a condition, then compile the string back together. Basically, I am pulling social media posts and want #s and @s to show up in blue.

Does anyone have any experience doing something like this? In that past, I would probably use something like PHP's explode() function, but perhaps there are more elegant methods.

necrotic
Aug 2, 2005
I owe my brother big time for this!

Buckhead posted:

I need to process a string word by word and see if certain words match a condition, then compile the string back together. Basically, I am pulling social media posts and want #s and @s to show up in blue.

Does anyone have any experience doing something like this? In that past, I would probably use something like PHP's explode() function, but perhaps there are more elegant methods.

If you want to avoid using gsub, you could split and then join the string:

Ruby code:
require 'set'
def mark_things(str)
  markable = %w(#s @s).to_set # Use a set for O(1) include?

  str.split(' ').map do |word|
    if markable.include?(word) # If it's not specific words, and literally any hashtag or user, then do `word =~ /^#|@/` instead
      "<span class='marked'>#{word}</span>"
    else
      word
    end
  end.join(' ')
end

kayakyakr
Feb 16, 2004

Kayak is true
Anyone know of a gem that guesses at word/phrase abbreviation?

I've got to turn team names into abbreviations in some sort of clever way. Say, Texas Tech University would become TTU while Wisconsin would become Wisc.

If not, it shouldn't be too hard to create. Multiple words just take the first letter of each word (leaving out a, of, and, to, the, and any other short words that don't generally get capitalized). Single words just take the first 4 letters.

MasterSlowPoke
Oct 9, 2005

Our courage will pull us through

Buckhead posted:

I need to process a string word by word and see if certain words match a condition, then compile the string back together. Basically, I am pulling social media posts and want #s and @s to show up in blue.

Does anyone have any experience doing something like this? In that past, I would probably use something like PHP's explode() function, but perhaps there are more elegant methods.

Ruby code:
"lets #fart it up @butt".split(' ').collect { |word| ['#','@'].include?(word[0]) ? word.upcase : word }.join(' ')
Obviously use something other than upcase to tag the words.

edit: okay I must have opened this tab a long time ago and never looked at it

MasterSlowPoke fucked around with this message at 18:35 on Apr 6, 2015

Gmaz
Apr 3, 2011

New DLC for Aoe2 is out: Dynasties of India

quote:

# Use a set for O(1) include?
That's nice, never realized this.

necrotic
Aug 2, 2005
I owe my brother big time for this!

Gmaz posted:

That's nice, never realized this.

Yeah, its implemented as a Hash underneath, so anything looking for a specific value just maps to a hash key.

Buckhead
Aug 12, 2005

___ days until the 2010 trade deadline :(

necrotic posted:

If you want to avoid using gsub, you could split and then join the string:

Ruby code:
require 'set'
def mark_things(str)
  markable = %w(#s @s).to_set # Use a set for O(1) include?

  str.split(' ').map do |word|
    if markable.include?(word) # If it's not specific words, and literally any hashtag or user, then do `word =~ /^#|@/` instead
      "<span class='marked'>#{word}</span>"
    else
      word
    end
  end.join(' ')
end

Very cool, thank you! Haven't had a chance to test fully but I see what are you doing here.

Sub Par
Jul 18, 2001


Dinosaur Gum
I have a table that tracks which users have access to which resources, so it's just user_id and resource_id. I want to introduce a function where an admin can give 5 random users access to a given resource. I'm trying to think through the most efficient way to find 5 users that don't already have access to the resource. I know exactly how I'd write this in SQL but I can't think of a way to make this "rails-y". I would do:

code:
select top 5 id
from Users
where not exists (
     select 'X'
     from UserResources
     where UserResources.user_id = Users.id
          and UserResources.resource_id = 1)
order by newid()
I am going to just do this with raw SQL for now but I'm wondering (hoping?) there's a concise way to do this that i just don't know?

Simone Poodoin
Jun 26, 2003

Che storia figata, ragazzo!



I did something like this in a demo app

code:
class Page < ActiveRecord::Base
	belongs_to :site
	has_and_belongs_to_many :components, join_table: "pages_components"

	scope :without_components, -> {
	  includes(:pages_components).where(:pages_components => { :page_id => nil })
	}

	scope :with_components, -> {
	  joins(:pages_components)
	}

end
The query generated by without_components is

code:
SELECT "pages"."id" AS t0_r0, "pages"."site_id" AS t0_r1, "pages"."name" AS t0_r2, "pages"."description" AS t0_r3, 
"pages"."created_at" AS t0_r4, "pages"."updated_at" AS t0_r5, "pages_components"."page_id" AS t1_r0, 
"pages_components"."component_id" AS t1_r1 
FROM "pages" 
LEFT OUTER JOIN "pages_components" ON "pages_components"."page_id" = "pages"."id" 
WHERE "pages_components"."page_id" IS NULL

Sub Par
Jul 18, 2001


Dinosaur Gum
Excellent, thanks. I'll play around with this.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

EVGA Longoria posted:

Not talking about writing a DSL. Talking about using a DSL (Sinatra) getting penalized by CodeClimate.

If your Sinatra app is big enough that you are bothering to use Code Climate on it and care about your grade, make it a Rails app.

xtal
Jan 9, 2011

by Fluffdaddy

Cocoa Crispies posted:

If your Sinatra app is big enough that you are bothering to use Code Climate on it and care about your grade, make it a Rails app.

Sinatra is a great choice for large applications. Well, the HTTP server and router part of it.

Pardot
Jul 25, 2001




Cocoa Crispies posted:

If your Sinatra app is big enough that you are bothering to use Code Climate on it and care about your grade, make it a Rails app.

nope rails sucks I say as I'm on a flight to railsconf

kayakyakr
Feb 16, 2004

Kayak is true

Pardot posted:

nope rails sucks I say as I'm on a flight to railsconf

you suck where's railsconf this year?

necrotic
Aug 2, 2005
I owe my brother big time for this!

kayakyakr posted:

you suck where's railsconf this year?

ATL

I should've gone considering its right around the corner. Oh well!

Buckhead
Aug 12, 2005

___ days until the 2010 trade deadline :(
I am being returned a hash from an API with two identical keys. I need to save the first and second value to separate variables.

code:
{
	thumbnails {
		{ [small => "smallurl1..."
		  medium => "mediumurl1..."]
		[ small => "smallurl2..."
		  medium => "mediumurl2..."]
	}
}
I am currently using a counter to loop through them and assign to the appropriate ActiveRecord value. Is there a better way to do this?

code:
      i = 0
      newcard["thumbnails"].each do |url|
        if i == 0
          postcard.thumbnail_front_url = url["medium"]
        else
          postcard.thumbnail_back_url = url["medium"]
        end
        i = i + 1
      end

necrotic
Aug 2, 2005
I owe my brother big time for this!

Buckhead posted:

I am being returned a hash from an API with two identical keys. I need to save the first and second value to separate variables.

Looks like it will always be two values, so I'd just do this:

Ruby code:
postcard.thumbnail_front_url = newcard['thumbnails'].first['medium']
postcard.thumbnail_back_url = newcard['thumbnails'].last['medium']
edit:

Also, there's Enumerator#each_with_index so you don't have to increment your own counter.

necrotic fucked around with this message at 18:14 on Apr 21, 2015

Buckhead
Aug 12, 2005

___ days until the 2010 trade deadline :(
Thank you necrotic! You guys are awesome. Always good to learn these new functions.

edit: I also emailed the designers of that specific API and told them to have unique endpoints. Seems like bad design to rely on the order of the hash, rather than specific endpoints.

Buckhead fucked around with this message at 20:40 on Apr 21, 2015

no_funeral
Jul 4, 2004

why
Anybody have ideas about how to serve assets from S3, but using a relative path, aka faking that they're served from my web app? I'm trying to use pano2vr player to build an HTML5 Virtual tour, and it requires that the images and XML file that builds the tour be served from the same directory, on my app.

Simone Poodoin
Jun 26, 2003

Che storia figata, ragazzo!



I have done something similar to that before, using an assets controller

code:
class AssetsController < ApplicationController

  def index
    redirect_to self.build_s3_url(params[:filename])
  end

  def build_s3_url(filename)
    ...
  end

end
In my case it was used for access restriction to some docs and it was more complex than that. Not sure if the player will like the redirects but it might be worth a shot.

no_funeral
Jul 4, 2004

why

Drogadon posted:

I have done something similar to that before, using an assets controller

code:
class AssetsController < ApplicationController

  def index
    redirect_to self.build_s3_url(params[:filename])
  end

  def build_s3_url(filename)
    ...
  end

end
In my case it was used for access restriction to some docs and it was more complex than that. Not sure if the player will like the redirects but it might be worth a shot.

Nice, thank you. All I need is for the XML file that the pano2vr player reads to have relative paths to the source images. For example, this is what the XML looks like

code:
<?xml version="1.0" encoding="UTF-8"?>
<panorama>
<!-- Pano2VR 3.1.4 panorama configuration -->
<view fovmode="0">
<start pan="269.5" tilt="-0.5" fov="70"/>
<min pan="0" tilt="-90" fov="5"/>
<max pan="360" tilt="90" fov="120"/>
</view>
<autorotate speed="0.100" delay="2.00" returntohorizon="2.000" startloaded="0" />
<input tilesize="1000" tilescale="1.01" tile0url="./Living Room_o_0.jpg" tile1url="./Living Room_o_1.jpg" tile2url="./Living Room_o_2.jpg" tile3url="./Living Room_o_3.jpg" tile4url="./Living Room_o_4.jpg" tile5url="./Living Room_o_5.jpg" />
<userdata title="" description="" author="realfoto Victoria" datetime="" copyright="&#169;realfoto" source="" info="www.realfotovictoria.com" comment="" />
<control sensitivity="8" simulatemass="1" lockedmouse="0" lockedkeyboard="0" lockedwheel="0" invertwheel="0" speedwheel="1" dblclickfullscreen="1" invertcontrol="1" />
<sounds>
</sounds>
</panorama>
Where all I'm changing are the tileXurl entires. I'll try this out, thanks!

KoRMaK
Jul 31, 2012



This is a completely crazy bug but I have no idea what the hell.

Code changes I make to models don't get loaded unless I completely exit my shell. My workflow is normally:
1. open terminal
2. rails s
3. develop, change stuff, reload page
4. happiness

Now I have this bug where stuff won't update in server mode or console. So no my workflow is
1. open terminal
2. rails c
3. load object
4. object.some_relationship #bugs out here saiyng the relationship doesn't exist
5. exit console, exit terminal
6. launch terminal, rails c
7. object.some_relationship #works now, but only after a terminal exit


So I have to completely exit the terminal if I make changes in my text editor. What the hell?



e: Fixed it, changed some init settings and it started working. Wierd that it required me to exit the terminal though. I think it was fixed by remove config.reload_classes_only_on_change = false

KoRMaK fucked around with this message at 03:48 on Apr 24, 2015

necrotic
Aug 2, 2005
I owe my brother big time for this!

KoRMaK posted:

e: Fixed it, changed some init settings and it started working. Wierd that it required me to exit the terminal though. I think it was fixed by remove config.reload_classes_only_on_change = false

Yeah that setting will do it. And rails will only reload files from app/ and lib/, config/ file changes require a full reboot of the app. Not sure why you had to exit your terminal (I assume you mean like Terminal.app or iTerm2.app, not the rails console).

KoRMaK
Jul 31, 2012



I'm trying to use cancancan in my mailer views, but apparently "can?" isn't being included. How do I get can included on a mailer? I've tried including it via a helper and require but o luck.

e: NM, I got it. Just had to delegate to it in the helper.

KoRMaK fucked around with this message at 21:39 on May 1, 2015

Chilled Milk
Jun 22, 2003

No one here is alone,
satellites in every home
Security-ish question.

I'm currently working on a migration path for users of a few largely similiar legacy apps into this one new system. Since a user may have had an account on multiple sites and for Business Reasons the auth system has changed I need a mechanism for users to 'claim' their old accounts and merge the data into their new one. I've got the merging part in place and unit tested and whatnot but I wanted to make sure my idea for the workflow for it is sound. Basically, like how a password reset might go


  • User logs in, goes to Claim old account or w/e
  • User fills in the email address of the old account
  • System creates an AccountClaim record, with the user_id, email they input, and generates some random token with SecureRandom.urlsafe_base64
  • System mails out a link to the specified address with that token
  • User clicks link
  • System looks for an AccountClaim by that token, and probably makes sure it matches the user that is logged in
  • If found, system looks up old accounts by that email address and 'merges' them into the users current account, tosses the old records, and flags the AccountClaim as done.

fantastic in plastic
Jun 15, 2007

The Socialist Workers Party's newspaper proved to be a tough sell to downtown businessmen.
What happens if Alice puts Bob's email address in the "user fills in the email address of the old account" step?

kayakyakr
Feb 16, 2004

Kayak is true

Tao Jones posted:

What happens if Alice puts Bob's email address in the "user fills in the email address of the old account" step?

Seems like Bob would get an email asking him to claim his account?

That's fairly close to a reset password flow, which is fairly standard.

Chilled Milk
Jun 22, 2003

No one here is alone,
satellites in every home

kayakyakr posted:

Seems like Bob would get an email asking him to claim his account?

That's fairly close to a reset password flow, which is fairly standard.

Yeah, that's what I was going for. There'd be some warning text, and it could check that the user who originated it is the same one who clicked the link.

fantastic in plastic
Jun 15, 2007

The Socialist Workers Party's newspaper proved to be a tough sell to downtown businessmen.

kayakyakr posted:

Seems like Bob would get an email asking him to claim his account?

That's fairly close to a reset password flow, which is fairly standard.

Ah, okay. From the way I was reading the flow, it seemed like there'd be an AccountClaim with Alice's user_id and Bob's email address, which might be dangerous if Alice is evil and tricks Bob.

Sil
Jan 4, 2007

The Milkman posted:

Security-ish question.

I'm currently working on a migration path for users of a few largely similiar legacy apps into this one new system. Since a user may have had an account on multiple sites and for Business Reasons the auth system has changed I need a mechanism for users to 'claim' their old accounts and merge the data into their new one. I've got the merging part in place and unit tested and whatnot but I wanted to make sure my idea for the workflow for it is sound. Basically, like how a password reset might go


  • User logs in, goes to Claim old account or w/e
  • User fills in the email address of the old account
  • System creates an AccountClaim record, with the user_id, email they input, and generates some random token with SecureRandom.urlsafe_base64
  • System mails out a link to the specified address with that token
  • User clicks link
  • System looks for an AccountClaim by that token, and probably makes sure it matches the user that is logged in
  • If found, system looks up old accounts by that email address and 'merges' them into the users current account, tosses the old records, and flags the AccountClaim as done.

Why not just automatically migrate everyone and let them login with their old passwords?

kayakyakr
Feb 16, 2004

Kayak is true

Sil posted:

Why not just automatically migrate everyone and let them login with their old passwords?

secret key used to hash the passwords is going to be different across the legacy apps. Hashing methodology might not even be compatible.

You could create users and merge accounts automatically keying on email and just force users to reset their password when they try to sign up with an email already in the system, though.

Gmaz
Apr 3, 2011

New DLC for Aoe2 is out: Dynasties of India
I got 99 problems and RVM is one.

So I open up the terminal (on Ubuntu 14.04) and:

code:
>> which ruby
/home/me/.rvm/rubies/ruby-2.2.2/bin/ruby

>> cd myapp
>> rails s
The program 'rails' can be found in the following packages:
 * ruby-railties-3.2
 * ruby-railties-4.0

>> rvm use 2.2.2
Using /home/me/.rvm/gems/ruby-2.2.2  # different folder, still in .rvm though???
>> which ruby
/home/me/.rvm/rubies/ruby-2.2.2/bin/ruby  # still the old folder

>> rails s
# server and everything working normal
:psyduck:

This is happening after I pull an update of the app from the repo and ran:

rvm install 2.2.2
rvm use 2.2.2 - default
bundle install.

Now I have to run rvm use 2.2.2 every drat if I want to work on the app, before that everything worked fine. I don't have much experience with RVM since I use rbenv on other computers, and basically I have no idea WTF is going on whatsoever.

Gmaz fucked around with this message at 15:08 on May 11, 2015

kayakyakr
Feb 16, 2004

Kayak is true
add a .ruby-version and .ruby-gemset file to root of your project. Now it'll switch to the proper ruby and gemset every time.

(note: requires RVM to be properly installed in your shell profile)

Adbot
ADBOT LOVES YOU

Chilled Milk
Jun 22, 2003

No one here is alone,
satellites in every home
You could also try

rvm get stable --auto-dotfiles

If you don't mind it mucking with your dotfiles and just want to be fairly sure it's getting loaded properly. It doesn't do anything obnoxious in my experience

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply