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
Big Nubbins
Jun 1, 2004

A MIRACLE posted:

Wow, that seems kind of awkward, I didn't know people still inlined ruby in their javascript code. I hate to recommend js frameworks since it seems like you're already really far along with this method, but I've been really happy using either Angular, Backbone, or Knockout.js (with underscore.js as a utility belt) for my ajax-y goodness.

I'd also give Spine.js a look as an alternative to Backbone. Spine is written in Coffeescript, has no dependencies, and is teeny tiny. After learning Coffeescript, I found that it made me love Javascript more, but also never want to write Javascript again, if you know what I mean. There are some ugly parts of the syntax (mixed array/hash objects, I'm looking at you), but I find it much more readable, concise, and faster to write. Unlike Backbone, Spine doesn't really have a concept of a view, so you must plug your own templating solution into it. I use HAML/Coffeescript through the awesome haml_coffee_assets gem.

Adbot
ADBOT LOVES YOU

Physical
Sep 26, 2007

by T. Finninho

prom candy posted:

After seeing your other response I really would advise you to put these bits into partials rather than the helper. Partials are great for this kind of thing. I just built a survey-builder type system for an app I was working on and the surveys are all built out of partials, it keeps the code pretty clean.

code:
          - question_group.questions.each do |question|
            .question
              %h2
                = question.title
                = question.required
              = question.explanation_text
              .answer= render question.answer_partial, :f => f, :question => question
(This is HAML but you should be able to see what I mean)

Hmm yea maybe. I just don't want to end up with a partial for each field. I guess I can try to write one partial and see how far that gets me with the variables I pass in. My boss indicated that partials probably wouldn't be the right solution, but I think that's because he was thinking their might be a ton of files. I'll ask him what his hesitations on using partial were.

This is only the first layer, I don't want to have partials 3 or 4 levels deep when we do this to the other items that wrap around these ones. Is having partials nested that deep keeping with the RoR mindset?

prom candy
Dec 16, 2005

Only I may dance
Someone else may disagree with me but I personally like to use partials as little jigsaw pieces when I need to build something dynamically like this. It keeps your code nice and separated and then the view that's responsible for organizing the partials isn't filled with the actual field code so it's really easy for someone to see what's going on at a glance.

Take a look at how rails_admin uses partials to build up their dynamic forms

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Shame Boner posted:

I'd also give Spine.js a look as an alternative to Backbone. Spine is written in Coffeescript, has no dependencies, and is teeny tiny. After learning Coffeescript, I found that it made me love Javascript more, but also never want to write Javascript again, if you know what I mean. There are some ugly parts of the syntax (mixed array/hash objects, I'm looking at you), but I find it much more readable, concise, and faster to write. Unlike Backbone, Spine doesn't really have a concept of a view, so you must plug your own templating solution into it. I use HAML/Coffeescript through the awesome haml_coffee_assets gem.

I'll have to check Spine out, but the main reason I shy away from Backbone is the inevitable function-pointer-callback soup I get mired in for trying to manually render elements asynchronously. The MVVM pattern in Angular seems to solve this problem nicely.

Also, I'm not entirely convinced Coffeescript is better than plain JS. Prettier? Definitely. I'm probably going to wait out the whole "compiles to javascript" language battle that seems to be happening right now and go with the community consensus.

prom candy
Dec 16, 2005

Only I may dance
I don't know if CoffeeScript is the right choice for a huge Javascript-based app, but for your standard "need to write some stuff to complement my standard Rails app" it's really handy.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

prom candy posted:

I don't know if CoffeeScript is the right choice for a huge Javascript-based app, but for your standard "need to write some stuff to complement my standard Rails app" it's really handy.

For a huge JavaScript-based app, CoffeeScript is a better choice than JavaScript. There's simply less typing to do and things to mess up in CoffeeScript, and it's not noticeably more difficult to work with in a Rails app.

Basecamp is as much CoffeeScript as Ruby: http://37signals.com/svn/posts/3094-code-statistics-for-basecamp-next

CoffeeScript is JavaScript without line noise: http://37signals.com/svn/posts/2975-sam-talks-javascript-on-the-changelog

GitHub prefers CoffeeScript for new JS development, such as their Hubot campfire bot: https://github.com/github/hubot

CoffeeScript is designed to write better JavaScript than you will: http://readwrite.com/2011/01/07/interview-coffeescript-jeremy-ashkenas

The compile step isn't something to worry about : Rails comes configured out of the box to do it for you. Fundamentally it's not a JavaScript replacement, just a more powerful way to write javaScript.

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.
I want to build a dashboard type thing in rails that will run some SQL queries on a database (not the rails persistence database - a business database elsewhere that already exists), and then display charts of the results in the web UI.

Any recommendations for a technique to do this? I was thinking of using google's chart API.

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Active Admin + your favorite SVG based javascript graphics library.

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.

A MIRACLE posted:

Active Admin + your favorite SVG based javascript graphics library.

Is Active Admin a good way to run arbitrary SQL on an unrelated database though?

prom candy
Dec 16, 2005

Only I may dance
You'll probably want to look up some articles on working with legacy databases. Basically you need to add some extra info to your models that will let them talk to the old database.

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

If all you care about is running your own SQL commands, look into using the Sequel gem instead of ActiveRecord. But I recommended ActiveAdmin because I think it has a pretty interface :3

Obsurveyor
Jan 10, 2003

Pardot posted:

Ruby and Sinatra is better to start out with than Ruby and Rails. It's also better to end up at. Rails is good for the middle.

I know this is from way back in March(catching up on thread) but listen to Pardot here, it's the absolute truth.

prom candy
Dec 16, 2005

Only I may dance
Every time I go to build a Sinatra app I end up missing a lot of the Rails niceties that I'm so accustomed to.

Doc Hawkins
Jun 15, 2010

Dashing? But I'm not even moving!


I think that past a certain scale, it's easier to run an app as a network of independently scalable single-purpose services than a single monolithic Rails project.

I also think that maybe twenty companies in the world have projects which have reached that scale.

prom candy
Dec 16, 2005

Only I may dance
Most of the apps I develop are either really simple, or they're complex but they're used by small organizations so I never really end up having to deal with scaling at the huge public SaaS level. If it does come to that point good app design should make it hopefully not too difficult to replace pieces of your site with separate services.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Doc Hawkins posted:

I think that past a certain scale, it's easier to run an app as a network of independently scalable single-purpose services than a single monolithic Rails project.

I also think that maybe twenty companies in the world have projects which have reached that scale.

There's a (not uploaded to Vimeo yet) RICON presentation from a Twitter engineer, about the process of moving from one monolithic Rails application (known as "monorail") to a service-oriented architecture, mostly because different parts need to be tuned and scaled differently.

However, your application isn't Twitter. Go ahead and build it as a monolithic Rails app and when you're big enough to have to split it up into separate apps in order to scale it well, you've already won.

For what it's worth, I work daily on an app that's several Sinatra apps that communicate, and I pray for death Rails daily.

prom candy
Dec 16, 2005

Only I may dance
Probably the most important thing is to reduce coupling as much as possible. That way if the day comes that you need to go crazy with scaling you can, but you're also not wasting a ton of time up front trying to scale a product that may never need it.

Physical
Sep 26, 2007

by T. Finninho
I've been trying to wrap my head around Sinatra. Had a little paradigm shift happen in my mind on how this whole thing works. Gems are Ruby specific, not RoR specific, operate outside of rails, and in fact rails is a gem. I thought the rails gem was there for some superficial reason, like an include or something [size="xx-small"]I don't know I stopped obsessively dissecting things sometime ago and haven't really had a reason to examine this platform.[/size]

Reading the docu on Sinatra I still don't really see how to use it, I need pictures and visualizations of requests and dataflows, but it looks like its RESTful and replaces Rails in some unspecific (to me) way.

But with the Sinatra Gem the platform name becomes "Ruby on Sinatra" eh? :mmmhmm::respek::quagmire:

Obsurveyor
Jan 10, 2003

I actually meant that quote more in the general sense. You don't have to limit rails to monolithic apps and you don't have to limit Sinatra to service oriented architectures.

Lately, I've become disenchanted with rails. It feels like an awful lot of it is too magic and I'm spending more time figuring out the right incantations than just building apps, especially as my applications have gotten more complex. Routing and routing helpers are particularly annoying. It sure seems that updates are fraught with deprecations and frankly, just happen too fast with too much bloat, it's a moving target that I am a bit tired of trying to keep hitting.

I'm seriously considering migrating away from rails and into something that uses sinatra as a base. RESTful, like padrino, but even lighter weight, just snagging the best bits. I really like the idea from padrino of the routes being right there in the controller instead of hidden away in their own file. I haven't made a decision yet because I'm sure there's all kinds of things I take for granted that rails gives me. I need to determine if not having those things is going to impact development time negatively.

I still like rails, learning it has taught me a lot about how web applications are built in ruby. With the heavier emphasis the rails team has put on breaking things out into gems instead of making them part of rails, I can still use a lot of the same things.

Physical posted:

Reading the docu on Sinatra I still don't really see how to use it, I need pictures and visualizations of requests and dataflows, but it looks like its RESTful and replaces Rails in some unspecific (to me) way.
Sinatra: Up and Running is a great book for learning all about Sinatra. You can easily finish it in less than a day. There's Sinatra The Book too, that's free. I haven't gone through this one but the padrino guys like it.

Obsurveyor fucked around with this message at 20:20 on Oct 30, 2012

Physical
Sep 26, 2007

by T. Finninho

Obsurveyor posted:

I actually meant that quote more in the general sense. You don't have to limit rails to monolithic apps and you don't have to limit Sinatra to service oriented architectures.

Lately, I've become disenchanted with rails. It feels like an awful lot of it is too magic and I'm spending more time figuring out the right incantations than just building apps, especially as my applications have gotten more complex. Routing and routing helpers are particularly annoying. It sure seems that updates are fraught with deprecations and frankly, just happen too fast with too much bloat, it's a moving target that I am a bit tired of trying to keep hitting.

I'm seriously considering migrating away from rails and into something that uses sinatra as a base. RESTful, like padrino, but even lighter weight, just snagging the best bits. I really like the idea from padrino of the routes being right there in the controller instead of hidden away in their own file. I haven't made a decision yet because I'm sure there's all kinds of things I take for granted that rails gives me. I need to determine if not having those things is going to impact development time negatively.

I still like rails, learning it has taught me a lot about how web applications are built in ruby. With the heavier emphasis the rails team has put on breaking things out into gems instead of making them part of rails, I can still use a lot of the same things.

Sinatra: Up and Running is a great book for learning all about Sinatra. You can easily finish it in less than a day. There's Sinatra The Book too, that's free. I haven't gone through this one but the padrino guys like it.
I might check that out some day.

On a rails note, how do I make a class/object that doesn't tie to a database? I'm using a hash right now, but it would be easier I think if I could just do
code:
myobj.name = "myname"
myobj.zip = "55555"
Do I do this with attr_accessors on a model or something? Or would I create a ruby class (or would that be against RoR best practices)?

I never thought of creating a ruby class before, I thought only models were available and they HAD to be tied to a db table. Using a ruby class would have answered a question I had way back about getting data from a model and manipulating it at runtime without the results going back to the DB row.

Physical fucked around with this message at 20:33 on Oct 30, 2012

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Physical posted:

Do I do this with attr_accessors on a model or something? Or would I create a ruby class (or would that be against RoR best practices)?

I never thought of creating a ruby class before, I thought only models were available and they HAD to be tied to a db table. Using a ruby class would have answered a question I had way back about getting data from a model and manipulating it at runtime without the results going back to the DB row.

The "app/models" directory is filled with Ruby classes that happen to be used as models. If you make one that doesn't inherit from ActiveRecord::Base (or any other database mapper) it won't be persisted in the database.

For complicated processes it's usually best to put logic in a model there instead of in the controller.

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Depending on what you're trying to do you could look into extending existing ActiveModel classes with ActiveSupport::Concern (which usually go in app/concerns), or just creating your own folder app/myclasses/my_class.rb, and including it in whatever file you're using the class in. Alternately, load it in your environment config by adding the path there to make it available to all classes.

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.
Following on from my above question, I've found a way to use ActiveRecord infrastructure to make connections to a non-rails database:

code:
class NonRailsDb < ActiveRecord::Base
  establish_connection(:prod_logging_database)
  
  def self.get_objects
    self.connection.select_value("SELECT COUNT(*) FROM users")  # Put arbitrary SQL here.
  end
end
The problem with this is that I cannot create an instance of NonRailsDb, because ActiveRecord assumes a table exists with that name. Can I circumvent this behaviour? I want to use this class as a view model of sorts... but I don't want to have to create a database table to fool rails.

Pardot
Jul 25, 2001




Lexicon posted:

Following on from my above question, I've found a way to use ActiveRecord infrastructure to make connections to a non-rails database:


Give sequel a looksee http://sequel.rubyforge.org/

Here's some stuff from a thing wrote the other day

Ruby code:
 def reset_target_stats!
    target_db.execute "select pg_stat_statements_reset()"
  end

  def target_db
    TARGET_DB
  end

  def connections
    target_db[:pg_stat_activity].count
  end

  def stat_statements
    target_db[:pg_stat_statements]
      .select(:query, :calls, :total_time)
      .exclude(query: '<insufficient privilege>')
      .all
  end

  def cache_hit
    target_db[:pg_statio_user_tables]
      .select("(sum(heap_blks_hit) - sum(heap_blks_read)) / sum(heap_blks_hit) as ratio".lit)
      .first[:ratio]
      .to_f
  end

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.


Speaking of Sequel, I've been using it a lot for production DB scripting here at the office, and was wondering if there's a faster way to do this:

Ruby code:
DB = Sequel.connect('mysql://....AWS/mydb')

f = File.open("my_data.csv", 'r')

DB.transaction do
  until (a = f.gets).nil?
    a = a.strip.split(/,/)
    DB.run("update my_table set some_val=#{a[1]} where some_id=#{a[0]}")
  end
end
Basically a mass update of a bunch of rows, changing only one field per row to a corresponding value. This is more of a general DB question but in the context of the Sequel gem I guess. I wrapped it in a `transaction` but I feel like it might still be opening and closing connections in my until loop (I know this is slow).

Physical
Sep 26, 2007

by T. Finninho

A MIRACLE posted:

Depending on what you're trying to do you could look into extending existing ActiveModel classes with ActiveSupport::Concern (which usually go in app/concerns), or just creating your own folder app/myclasses/my_class.rb, and including it in whatever file you're using the class in. Alternately, load it in your environment config by adding the path there to make it available to all classes.
I created a folder in my app directory called classes with a file classes/input_field.rb defined as
code:
module InputField

end
then I tried including it in a controller but I keep getting
uninitialized constant MyController::InputField

Not sure what I am missing here. Eclipse knows that it exists, so the intellisense is working.

prom candy
Dec 16, 2005

Only I may dance
I think you want a class here, not a module. You can put non-active record classes into your app/models folder, no reason to get all crazy.

Physical
Sep 26, 2007

by T. Finninho

prom candy posted:

I think you want a class here, not a module.
Yea but don't I have to include the class in a module? Are modules only allowed inside of the lib folder?

And in any case, how do I get RoR to know where to find this thing? Everything I've been reading says this should work.

Physical fucked around with this message at 21:53 on Oct 30, 2012

prom candy
Dec 16, 2005

Only I may dance
Nope, you can literally just create a class, (or Plain Ol' Ruby Object as they're sometimes called) in your models folder and then interact with it like anything else.

(Highly recommended reading: http://objectsonrails.com/)

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Physical posted:

I created a folder in my app directory called classes with a file classes/input_field.rb defined as
code:
module InputField

end
then I tried including it in a controller but I keep getting
uninitialized constant MyController::InputField

Not sure what I am missing here. Eclipse knows that it exists, so the intellisense is working.

What does your controller look like? Are you using relative pathing or including the path in your root environment?

Physical
Sep 26, 2007

by T. Finninho

A MIRACLE posted:

What does your controller look like? Are you using relative pathing or including the path in your root environment?
code:
class MyController < ApplicationController
  include InputField
end
I'm not sure how to include it in my root env (I'm assuming it's already taken care of since it's in the app directory).

e: Ok this worked require './app/classes/input_field.rb' but I'd rather use the method stated above. Looks classy.

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Physical posted:


I'm not sure how to include it in my root env (I'm assuming it's already taken care of since it's in the app directory).


Nope! Check this out:

config/application.rb posted:

Ruby code:
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W{
      #{config.root}/app/models/extensions 
      #{config.root}/app/models/concerns
      #{config.root}/lib 
      #{config.root}/lib/offers_observers
    }

e: looks like syntax highlighting is "broken" for string interpolation inside of a %w. What does SA use for syntax highlighting? Pygments?

A MIRACLE fucked around with this message at 22:08 on Oct 30, 2012

Doc Hawkins
Jun 15, 2010

Dashing? But I'm not even moving!


I have made a lot of oddly-named app subdirectories in my time, and I have never had to explicitly add them to an autoload config. Maybe that's only for lib/?

Physical
Sep 26, 2007

by T. Finninho

A MIRACLE posted:

Nope! Check this out:


e: looks like syntax highlighting is "broken" for string interpolation inside of a %w. What does SA use for syntax highlighting? Pygments?
Thanks found that shortly before you replied. Now my issue is variables.

But now it keeps acting like things are methods instead of variables.

Doing this
Ruby code:
module InputField
  class InputFields
    nameee = "nothin"
  end
end
Then this
Ruby code:
  def show
    _v = InputFields.new
    Rails.logger.info("_v.name #{_v.inspect}")
    _v.name = "asdfasdfasdf"
    Rails.logger.info("_v.name #{_v.name}")
  end
Yields
undefined method `name=' for #<InputField::InputFields:0xccb3a34>

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Physical posted:

Thanks found that shortly before you replied. Now my issue is variables.

But now it keeps acting like things are methods instead of variables.

Yeah... you haven't defined name as an instance/class variable for InputFields. There's a shortcut, attr_accessor :my_variable, which is like a getter/setter in C# for example.

edit:

Shortcut for doing this:
Ruby code:
module InputField
  class InputFields
    @nameee = "nothin"

    def nameee= val
      @nameee= val
    end
  end
end
It's all about exposing variables to the outside world. I still don't know why you're nesting this inside of a module though, unless you're going to add a bunch of different classes to it or something.

A MIRACLE fucked around with this message at 22:22 on Oct 30, 2012

Physical
Sep 26, 2007

by T. Finninho

A MIRACLE posted:

Yeah... you haven't defined name as an instance/class variable for InputFields. There's a shortcut, attr_accessor :my_variable, which is like a getter/setter in C# for example.
Holy poo poo I did namee and name. Forgot that I wanted to use namee in the controller. Even if I did spell it right I still have to use the attr_accessor.

Thanks for the help!

As for nesting inside a module, I thought I had to. When I drop the module part I get wrong argument type Class (expected Module)

e:Oh, I just have to drop the "include" command and it finds it on its own. So is include only for modules? If I didn't add the path to my application.rb as such
Ruby code:
config.autoload_paths += %W(#{config.root}/app/classes)
How would I include the class? Application::Classes:InputField or something?

Physical fucked around with this message at 22:29 on Oct 30, 2012

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Physical posted:

Holy poo poo I did namee and name. Forgot that I wanted to use namee in the controller. Even if I did spell it right I still have to use the attr_accessor.

Thanks for the help!

As for nesting inside a module, I thought I had to. When I drop the module part I get wrong argument type Class (expected Module)

If it's included in the Rails environment you don't have to for classes I think.

But yeah, to include something means that something is a module, and you want to use it as a mixin, ie have that module now be a part of your class, with all its methods and variables and what-not. Just require '../myfile' or whatever in the future, or have it in the environment already.

Physical
Sep 26, 2007

by T. Finninho
I don't get the difference between declaring variables in a class like this
Ruby code:
class InputField
  attr_accessor :nameee
  nameee = "nothin"
end

class InputField
  attr_accessor :nameee
  @nameee = "nothin"
end
I read this http://railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/, but besides the @@ vs @ I don't see why not to just drop the @ altogether. Also, it doens't look like they are getting set to the value when the class is created, I guess I have to do that in def initialize

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.


Use the def initialize constructor.

Ruby code:
class Jedi
  attr_accessor :name
  def initialize
    name = "Luke"
  end
end

class Sith
  attr_accessor :name
  def initialize
    @name = "Vader"
  end
end

puts Jedi.new.name #=> ""
puts Sith.new.name #=> "Vader"

Adbot
ADBOT LOVES YOU

Physical
Sep 26, 2007

by T. Finninho

A MIRACLE posted:

Use the def initialize constructor.

Ruby code:
class Jedi
  attr_accessor :name
  def initialize
    name = "Luke"
  end
end

class Sith
  attr_accessor :name
  def initialize
    @name = "Vader"
  end
end

puts Jedi.new.name #=> ""
puts Sith.new.name #=> "Vader"
Why did the Jedi version not work? What is the point of non-@ members, when are they appropriate?

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