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
Chilled Milk
Jun 22, 2003

No one here is alone,
satellites in every home
I"ve poked around Clojure stuff just to see what all the 'hype' was about, didn't hook me in. But I have become more and more interested in giving Elixir a whirl. I'm blessed with having to build lots of small and varied standalone apps and less the hulking aged monoliths so I haven't burned out on Rails yet. At least there's Lotus now for when that day comes and I want to stick with Ruby

Adbot
ADBOT LOVES YOU

Gmaz
Apr 3, 2011

New DLC for Aoe2 is out: Dynasties of India
I've been getting into Elixir lately too, the language creator (Jose Valim) is a core Rails contributor and the author of Devise authentication gem. The whole language runs on the Erlang VM (usually called BEAM), the syntax has some Ruby influences but the language is functional so in reality there is not so much crossover, still it's very interesting to learn especially if you want to build a system that can scale easily.

The performance of the Phoenix web framework (basically Rails of the Elixir world) is awesome, you can see requests being served in microseconds.

xenilk
Apr 17, 2004

ERRYDAY I BE SPLIT-TONING! Honestly, its the only skill I got other than shooting the back of women and calling it "Editorial".
I have an ActiveRecord question for you guys.

I have 3 models
- Trips
- Departures (Basically locations where buses leave from)
- DepartureDates (Links Departures + Trips and mentions a date and time)

I'm getting the trips with an upcoming departuredate with this statement:

Trip.joins(:departure_dates).where("departure_dates.leaves_on > ?", Time.now)


I want to add something to that statement so I only get the trip once and the departure that's closest to the current time.

I'm thinking I need some sort of group by, but other than that I'm kind of lost right now...

Pardot
Jul 25, 2001




This feels like you want DISTINCT ON (which is not the same as just DISTINCT), but I dont know how you get that through active record.

Thalagyrt
Aug 10, 2006

Pardot posted:

This feels like you want DISTINCT ON (which is not the same as just DISTINCT), but I dont know how you get that through active record.

If you're using Arel 6 (so Rails 4.2 and up) there's an Arel method for distinct_on.

code:
table = Arel::Table.new(:users)
table.project(Arel.star).distinct_on(table[:id]).to_sql

Peristalsis
Apr 5, 2004
Move along.
I'm setting up our project on a VM on my computer so I can work from home. I can't run rake db:setup, because the rake task is trying to use the test database, instead of the dev one. I've added

code:
ENV["RAILS_ENV"] = "development"
to the end of my environment.rb file, but it didn't help.

For now, I've changed the test entry to be the same as development in database.yml, which did get me past this issue, but I'd like to understand what I'm doing wrong. (And fix it, of course.)

kayakyakr
Feb 16, 2004

Kayak is true

Peristalsis posted:

I'm setting up our project on a VM on my computer so I can work from home. I can't run rake db:setup, because the rake task is trying to use the test database, instead of the dev one. I've added

code:
ENV["RAILS_ENV"] = "development"
to the end of my environment.rb file, but it didn't help.

For now, I've changed the test entry to be the same as development in database.yml, which did get me past this issue, but I'd like to understand what I'm doing wrong. (And fix it, of course.)

I believe rake db:setup does both production and test databases at the same time.

manero
Jan 30, 2006

kayakyakr posted:

I believe rake db:setup does both production and test databases at the same time.

Yeah, db:setup will create everything in one fell swoop.

Peristalsis
Apr 5, 2004
Move along.
Our other programmer (the UI guy, sort of) left, and now I have to maintain his code. Naturally, I immediately have a problem I haven't seen before.

They symptom is this: one of our forms has a list of files that is generated after the user selects an option on a pulldown box. This list shows up as it's supposed to in Firefox, but does not show up in Chrome.

After poking through his code, here's what I think is going on: There's a jQuery function assigned to the change event of the pulldown widget. This function uses an Ajax call to the form's controller to create an array of file info in an instance variable (@type_headers). The other javascript that runs in the view now depends on this controller instance variable being available in the view to populate the list of files. However, since the 'A' in Ajax stands for Asynchronous, there's no guarantee that this variable is ready before it's used in the other script. Apparently, Firefox is more likely to have it ready before it's used than Chrome is - presumably, they implement JavaScript differently. One piece of supporting evidence I have for this theory is that I did get the files to show in Chrome one time, when I had a bunch of debugging and alert statements in the code. I assume it just stalled things long enough for Chrome's JavaScript interpreter to catch up. If this is too hard to follow, let me know, and I'll try to draw a picture to clarify.

1) Is it even possible that it's doing this, or do I have to be misunderstanding the code somehow?
2) Is there an obvious fix?
  1. We've already frozen code for the current release (i.e. no more submitted projects, just fixes for bugs that can't wait for the next release (like this one)), and I'd prefer not to completely rewrite all the code for this functionality in the next couple of days.
  2. I know it's bad form to make Ajax calls synchronous, but is this an example of a case where it's justified? If I'm right about the cause of the problem, I think that would solve it with one small code change.
  3. Is there another, obvious or best-practice fix for this situation?
  4. Is there a canonical Right Way to do this in general, for if/when I do completely change the approach? That is, is there a standard way to populate one UI control with info from the database, based on what the user selects as the value of another UI control?

Peristalsis fucked around with this message at 18:34 on Aug 7, 2015

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder
Async errors are incredibly common but I don't think that's what you're dealing with. I might be misunderstanding though.

Peristalsis posted:

This function uses an Ajax call to the form's controller to create an array of file info in an instance variable (@type_headers).

The other javascript that runs in the view now depends on this controller instance variable being available in the view to populate the list of files.

This doesn't make any sense. A javascript function can't load data into a ruby instance attribute. What you could be doing is loading the list of file info into whatever (if any) literal string value the instance variable is at the time the ERB is compiled.

Or if you mean that both scripts are making ajaxing requests to the controller: keep in mind that each request instantiates a new controller. So, you can't have two requests trying to share data across an instance variable.

reread your post: Basically, my second point: It sounds like you're trying to share data from multiple requests across an instance variable. That's not going to work. I don't know why it is working.

DONT THREAD ON ME fucked around with this message at 19:27 on Aug 8, 2015

fantastic in plastic
Jun 15, 2007

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

So, if I'm understanding your description, you've got one AJAX call that's something like GET api/whatevers?q=foo that you fire off when a user selects an option in a select box. The API does whatever it does to handle that request and sends you the results, which you're setting to a variable and then using that variable for other code, which you theorize is executing before your variable is set.

You could try sticking your code that needs the variable into something like this:

code:
function awaitResponse() {
    if(typeof @yourVariable !== "undefined") {
        //do the thing here
    }
    else {
        setTimeout(awaitResponse, 250);
    }
}
That would check the variable every 250ms and if it's set to something, execute your code, otherwise wait another 250ms. There's probably a better way to do it, but I think that would at least help you prove your async hypothesis.

Peristalsis
Apr 5, 2004
Move along.

MALE SHOEGAZE posted:

Async errors are incredibly common but I don't think that's what you're dealing with. I might be misunderstanding though.


This doesn't make any sense. A javascript function can't load data into a ruby instance attribute. What you could be doing is loading the list of file info into whatever (if any) literal string value the instance variable is at the time the ERB is compiled.

Or if you mean that both scripts are making ajaxing requests to the controller: keep in mind that each request instantiates a new controller. So, you can't have two requests trying to share data across an instance variable.


Tao Jones posted:

So, if I'm understanding your description, you've got one AJAX call that's something like GET api/whatevers?q=foo that you fire off when a user selects an option in a select box. The API does whatever it does to handle that request and sends you the results, which you're setting to a variable and then using that variable for other code, which you theorize is executing before your variable is set.

You could try sticking your code that needs the variable into something like this:

code:
function awaitResponse() {
    if(typeof @yourVariable !== "undefined") {
        //do the thing here
    }
    else {
        setTimeout(awaitResponse, 250);
    }
}
That would check the variable every 250ms and if it's set to something, execute your code, otherwise wait another 250ms. There's probably a better way to do it, but I think that would at least help you prove your async hypothesis.


I probably wasn't clear, and it's still possible I'm fundamentally mis-understanding the code, but let me try to clarify, if only for the entertainment value. There's some pseudo-code at the bottom, if that's easier.

There's a form with an AJAX call that is routed to a method in the form's controller. That method uses the incoming data to populate an instance variable, which Rails automatically makes available back in the form. The form then uses that variable (@type_headers) to determine what to add to the form's display.

This seems to work okay in Firefox, but in Chrome, when the view code moves on (since it doesn't have to wait for the AJAX call to finish) and tries to use that instance variable to determine which parts of the form to show or repopulate, the variable hasn't been created yet (or at least it isn't available to the form yet). It's like a bad hack on a comp 101 assignment to get around figuring out the entire point of the assignment. Did I mention that extensive testing wasn't the forte of the developer who originally wrote this? Neither was elegant design.

Tentative resolution:
In any case, someone finally pointed out to me that I can retrieve the same info just using JavaScript to send a post command instead of using AJAX, and it should be synchronous by nature. I haven't tried to implement it yet, but I'll jump on it first thing Monday.


And this is a simplified version of how the code is set up.
This code is for entertainment purposes only. Do not attempt to use this code at home.
Form pseudo-code:
code:
<script>
  $("#TemplateSelectorPulldownThingy").change(function() {
    $.ajax(
      url:  "<%= populate_variable_path %>",
      data:  {obj_id: my_object.id}
    );
  });
</script>
An included javascript file
code:
$("#some_other_widget_i_haven't_tracked_down_yet).html("<%= escape_javascript(options_for_select(@some_list_offiles)) %>");
<% if(@type_headers) %>         <----  *** This is where the presence or absence of the variable is key ***
  $('#placeholder_element').append('<A bunch of HTML to populate the file info>')
  // Some code to make the elements appear on screen
<% end %>
And the controller code that is the target of the AJAX call
code:
def populate_variable
  ...
  @type_headers = <method to construct file variable and do other stuff> <--- *** Rails makes this variable available in the view **
  ...
end

Peristalsis fucked around with this message at 20:47 on Aug 8, 2015

Docjowles
Apr 9, 2009

I'm having my first real encounter with ruby and I have what is probably a really retarded question. Why does this ERB template not do what I expect? It's being run through Chef, if that matters:

code:
<% if @config.key?(:override_app_define) %>
export APPDEFINE="<%= @config[:override_app_define]%>"
<% else %>
export APPDEFINE="default"
<% end %>
In this case, the config hash does NOT have the key :override_app_define defined. But the template is still hitting that code path. And then the template gets rendered as

code:
export APPDEFINE=
There's nothing after the = sign because the key does not exist. Why is it doing this? I've tried about 50 different variants, all of which have the same behavior. Such as

code:
if @config.has_key?(:override_app_define)
if @config[:override_app_define].nil?
if @config[:override_app_define] == "" (just in case I am wrong and it is defined but just empty)

MasterSlowPoke
Oct 9, 2005

Our courage will pull us through
What is the contents of the @config hash there?

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

Docjowles posted:

I'm having my first real encounter with ruby and I have what is probably a really retarded question. Why does this ERB template not do what I expect? It's being run through Chef, if that matters:

What if you replace the whole thing with
code:
export APPDEFINE="<%= @config.fetch(:override_app_define, "default") %>"
What you have looks like it should work, but I've never used Chef, so there might be some specific weirdness related to that. Is @config actually just a Hash?

This is really a Rails thread, but there doesn't appear to be a general Ruby thread, or a Chef thread, so whatever.

Docjowles
Apr 9, 2009

... son of a bitch. Apparently I just needed to post this and go walk around the building for 5 minutes. Got it working, it had nothing to do with the ERB syntax at all. Was just using Chef wrong. Thanks for the tips, all.

:saddowns:

KoRMaK
Jul 31, 2012



Docjowles posted:

... son of a bitch. Apparently I just needed to post this and go walk around the building for 5 minutes. Got it working, it had nothing to do with the ERB syntax at all. Was just using Chef wrong. Thanks for the tips, all.

:saddowns:
I use this technique a couple times a day. It's saved me from hours of work troubleshooting a non-issue.

Peristalsis
Apr 5, 2004
Move along.
The last project of the developer who just left our team was to take our controlled vocabulary (e.g. valid options to use to populate a pulldown menu), which was defined in constant arrays in each model, and put it all into a single table, with columns for the class, the filed the options are for, and the term itself. The idea is that we can now add/delete/modify these vocabulary terms dynamically, without the need of a release, or even of restarting the server.

So, we went from this:
code:
my_model.rb

...

STATUS_ARRAY = ["Excellent", "Good", "Okay", "Bad"]
validates_inclusion_of :status, :in => STATUS_ARRAY
to this:
code:
my_model.rb

...

validates_inclusion_of :status, :in => ControlledVocabulary.get_vocab("MyModel", "status")
This was well and good, until I turned off caching in my dev environment, and the validations failed. Apparently, in production, Rails evaluates the validation code when the class is loaded, and then holds its results statically. So, on forms, where the same method is used to populate pulldown menus, everything works fine, because the menus are populated anew each time the form is loaded. But saving an object from the form using a new vocab term fails, because the model validation still has the old list of options in it.

My questions:
1) For our next release, I'm planning to replace each validates_inclusion_of validation with a custom method that retrieves the list dynamically. This seems to work in my testing so far. Is there a better approach, or any reason that this is a bad idea? I know this will slow down performance, but I doubt that it'll be significant, and I don't really see an alternative.
2) We're going ahead with the current release despite this problem. Even with this flaw, the system won't work any worse than before, and any changes to the controlled vocabulary have to come through us anyway. So, is there a way to force Rails to reload a class definition? If so, does it have any risks or side-effects (e.g. affect related or connected classes)? I know you can reload an ActiveRecord object, but classes don't seem to recognize the reload method.
3) Is there a better overall approach we should have used from the beginning?

Peristalsis fucked around with this message at 18:47 on Aug 26, 2015

kayakyakr
Feb 16, 2004

Kayak is true

Peristalsis posted:

The last project of the developer who just left our team was to take our controlled vocabulary (e.g. valid options to use to populate a pulldown menu), which was defined in constant arrays in each model, and put it all into a single table, with columns for the class, the filed the options are for, and the term itself. The idea is that we can now add/delete/modify these vocabulary terms dynamically, without the need of a release, or even of restarting the server.

So, we went from this:
code:
my_model.rb

...

STATUS_ARRAY = ["Excellent", "Good", "Okay", "Bad"]
validates_inclusion_of :status, :in => STATUS_ARRAY
to this:
code:
my_model.rb

...

validates_inclusion_of :status, :in => ControlledVocabulary.get_vocab("MyModel", "status")
This was well and good, until I turned off caching in my dev environment, and the validations failed. Apparently, in production, Rails evaluates the validation code when the class is loaded, and then holds its results statically. So, on forms, where the same method is used to populate pulldown menus, everything works fine, because the menus are populated anew each time the form is loaded. But saving an object from the form using a new vocab term fails, because the model validation still has the old list of options in it.

My questions:
1) For our next release, I'm planning to replace each validates_inclusion_of validation with a custom method that retrieves the list dynamically. This seems to work in my testing so far. Is there a better approach, or any reason that this is a bad idea? I know this will slow down performance, but I doubt that it'll be significant, and I don't really see an alternative.
2) We're going ahead with the current release despite this problem. Even with this flaw, the system won't work any worse than before, and any changes to the controlled vocabulary have to come through us anyway. So, is there a way to force Rails to reload a class definition? If so, does it have any risks or side-effects (e.g. affect related or connected classes)? I know you can reload an ActiveRecord object, but classes don't seem to recognize the reload method.
3) Is there a better overall approach we should have used from the beginning?

This is happening because your "in" statement is being run at load time since it's declared directly on the model.

use:

code:
validates_inclusion_of :status, :in => -> { ControlledVocabulary.get_vocab("MyModel", "status") }

Chilled Milk
Jun 22, 2003

No one here is alone,
satellites in every home

kayakyakr posted:

This is happening because your "in" statement is being run at load time since it's declared directly on the model.

use:

code:
validates_inclusion_of :status, :in => -> { ControlledVocabulary.get_vocab("MyModel", "status") }

Yep, you just need to wrap it in a lambda do that it's evaluated every time it's run, not just at load time.

Peristalsis
Apr 5, 2004
Move along.

kayakyakr posted:

This is happening because your "in" statement is being run at load time since it's declared directly on the model.

use:

code:
validates_inclusion_of :status, :in => -> { ControlledVocabulary.get_vocab("MyModel", "status") }

Thanks for the reply. When this validation is hit, the code is now throwing this error:

code:
wrong number of arguments (1 for 0)
The get_terms method takes two arguments, so that's not the issue, and I don't quite see what else to look at.

Two things to note - 1) I've never used lambdas before, so I may be missing something easy and obvious, and 2) if it matters this is in Rails 3.2.something, not Rails 4.

I'm going to do some Googling to see what I can find, but if there's an easy error/fix to point me to, I'd be much obliged.

Edit: It may just be an issue with the space separating the second arrow and the opening curly brace.

Peristalsis fucked around with this message at 21:27 on Aug 27, 2015

Chilled Milk
Jun 22, 2003

No one here is alone,
satellites in every home

Peristalsis posted:

Thanks for the reply. When this validation is hit, the code is now throwing this error:

code:
wrong number of arguments (1 for 0)
The get_terms method takes two arguments, so that's not the issue, and I don't quite see what else to look at.

Two things to note - 1) I've never used lambdas before, so I may be missing something easy and obvious, and 2) if it matters this is in Rails 3.2.something, not Rails 4.

I'm going to do some Googling to see what I can find, but if there's an easy error/fix to point me to, I'd be much obliged.

Where is it hitting that? Post the stack trace.

Peristalsis
Apr 5, 2004
Move along.

The Milkman posted:

Where is it hitting that? Post the stack trace.

Removing the space after the second arrow let me get to the new object page, but submitting the new object still raises the same exception:

code:
ArgumentError in SystemSettingsController#create

wrong number of arguments (1 for 0)
Rails.root: /vagrant

Application Trace | Framework Trace | Full Trace
app/models/system_setting.rb:21:in `block in <class:SystemSetting>'
app/controllers/system_settings_controller.rb:56:in `block in create'
app/controllers/system_settings_controller.rb:55:in `create'
system_setting.rb:21 is the line with this validation:
code:
validates_inclusion_of :environment, :in => ->{ ControlledVocabulary.get_terms("SystemSetting", "environment") }
My current guess is that the syntax for passing params to the get_terms method is different when it's in a lambda, but that's based on perusing a couple of marginally related pages.

Chilled Milk
Jun 22, 2003

No one here is alone,
satellites in every home

Peristalsis posted:

Removing the space after the second arrow let me get to the new object page, but submitting the new object still raises the same exception:

code:
ArgumentError in SystemSettingsController#create

wrong number of arguments (1 for 0)
Rails.root: /vagrant

Application Trace | Framework Trace | Full Trace
app/models/system_setting.rb:21:in `block in <class:SystemSetting>'
app/controllers/system_settings_controller.rb:56:in `block in create'
app/controllers/system_settings_controller.rb:55:in `create'
system_setting.rb:21 is the line with this validation:
code:
validates_inclusion_of :environment, :in => ->{ ControlledVocabulary.get_terms("SystemSetting", "environment") }
My current guess is that the syntax for passing params to the get_terms method is different when it's in a lambda, but that's based on perusing a couple of marginally related pages.

Try this:

code:
validates_inclusion_of :environment, {  :in => proc { ControlledVocabulary.get_terms("SystemSetting", "environment") } }

Peristalsis
Apr 5, 2004
Move along.

The Milkman posted:

Try this:

code:
validates_inclusion_of :environment, {  :in => proc { ControlledVocabulary.get_terms("SystemSetting", "environment") } }

That seems to work, thanks!

Do I need anything other than reading about procs and lambdas in ruby to understand how and why this works? I already understand that we're assigning a function to the validation instead of assigning the static results of calling that function once, but I'd like to know why the first attempts didn't work, why we need the whole :in clause explicitly in a hash, what the differences are between proc and lambda, etc.

Also, thank you for introducing me to the "stabby lambda" operator. Learning that name was probably the highlight of my week.

kayakyakr
Feb 16, 2004

Kayak is true

Peristalsis posted:

That seems to work, thanks!

Do I need anything other than reading about procs and lambdas in ruby to understand how and why this works? I already understand that we're assigning a function to the validation instead of assigning the static results of calling that function once, but I'd like to know why the first attempts didn't work, why we need the whole :in clause explicitly in a hash, what the differences are between proc and lambda, etc.

Also, thank you for introducing me to the "stabby lambda" operator. Learning that name was probably the highlight of my week.

The hash around the in clause shouldn't be required. Ruby will automatically hash up a collection of inferred keys and values that are in an arguments array. This may be wonky below Ruby 2.

Stabby lambda usage may also be wonky in rails 3. I was running under the assumption that you were on ruby 2, rails 4.

UPGRADE YOUR PROJECTS!

Chilled Milk
Jun 22, 2003

No one here is alone,
satellites in every home

kayakyakr posted:

The hash around the in clause shouldn't be required. Ruby will automatically hash up a collection of inferred keys and values that are in an arguments array. This may be wonky below Ruby 2.

Stabby lambda usage may also be wonky in rails 3. I was running under the assumption that you were on ruby 2, rails 4.

UPGRADE YOUR PROJECTS!

Yeah, from just looking at it, it seems okay, but it's not the first time I've come across needing the explicit {} even in Ruby 2/Rails 4. I'd think the stabby would work with those in, but I figured proc would be extra safe

Peristalsis
Apr 5, 2004
Move along.

kayakyakr posted:

The hash around the in clause shouldn't be required. Ruby will automatically hash up a collection of inferred keys and values that are in an arguments array. This may be wonky below Ruby 2.

Stabby lambda usage may also be wonky in rails 3. I was running under the assumption that you were on ruby 2, rails 4.

We are using Ruby 2.1.1 (at least, that's the version on my dev environment, prod might be slightly different).

kayakyakr posted:

UPGRADE YOUR PROJECTS!

I'd love to, but as the only developer for 3 projects, with another 1-2 projects starting soon, there's not much chance of being able to stop doing enhancements and bug fixes so I can make an upgrade that only I care about, and that, if we're lucky, will leave us exactly where we are now in terms of features, and if we're not lucky, will leave us with a bunch of new bugs. I am doing a small project at home in Rails 4, and I hope that will give me some experience with it for when we do have to migrate the current projects, and so I can use current stuff on the new projects we have coming.

It could be worse, our recently departed developer went to a company still on Rails 2 for their product.

A Big... Dog
Mar 25, 2013

HELLO DAD

Peristalsis posted:

It could be worse, our recently departed developer went to a company still on Rails 2 for their product.

oh god how

Peristalsis
Apr 5, 2004
Move along.

Yeah, but don't worry - it's only security software.

Peristalsis
Apr 5, 2004
Move along.
One of the .html.erb files I'm modifying has a couple of comments with extra dashes in the delimiters: <!--- comment here --->. It seems to work like other comments, except that it's confusing Sublime Text, which doesn't recognize the ending delimiter with the three dashes, and shades everything until the next correct end-comment delimiter as a comment. I don't see anything on Google about it, so I assume the guy who coded this just had a brain fart, but I wanted a quick sanity check to make sure it's not some special form of an HTML comment, or something meaningful to Rails.

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

Peristalsis posted:

One of the .html.erb files I'm modifying has a couple of comments with extra dashes in the delimiters: <!--- comment here --->. It seems to work like other comments, except that it's confusing Sublime Text, which doesn't recognize the ending delimiter with the three dashes, and shades everything until the next correct end-comment delimiter as a comment. I don't see anything on Google about it, so I assume the guy who coded this just had a brain fart, but I wanted a quick sanity check to make sure it's not some special form of an HTML comment, or something meaningful to Rails.

Pretty sure that's just a mistake. All erb really cares about is <%, <%= and the inverse of each. The parsing issue sounds like a bug with sublime text.

aunt jenkins
Jan 12, 2001

Peristalsis posted:

It could be worse, our recently departed developer went to a company still on Rails 2 for their product.

We have a customer still proudly running REE and Rails 1 in production with no plans to change. :monocle:

Peristalsis
Apr 5, 2004
Move along.

aunt jemima posted:

We have a customer still proudly running REE and Rails 1 in production with no plans to change. :monocle:

You know, I really need to remember to ask what versions of software are being used at the next job I apply/interview for. I guess using legacy systems and old tools is probably the rule rather than the exception, but I at least want to make sure I know what I'm getting into. And they should at least have given some thought to a migration plan, beyond "I guess we'll probably have to change at some point".

Chilled Milk
Jun 22, 2003

No one here is alone,
satellites in every home
Having a good time with the Furry Stormtrooper at Windy City Rails

Peristalsis
Apr 5, 2004
Move along.
Is anyone here good with Nokogiri?

I'm having an issue using XML DocumentFragments. Specifically, say I have
code:
xml_string = "<foo><name>My Foo</name><bar><name>My Foo's Bar</name></bar></foo>"
doc = Nokogiri::XML::Document
frag = Nokogiri::XML::DocumentFragment.parse(xml_string)
Then, I'd expect the doc and frag objects to be more or less the same, except that frag wouldn't have <?xml version="1.0"?> and any other XML boilerplate.

But, frag doesn't recognize that it has elements, even though doc does:

code:
doc.elements.count
=> 1
frag.elements.count
=> 0
frag.elements
=> []
Now, frag does have children, and does recognize that the first child (which it lists as an element object, even though it doesn't return it in element_children) has elements:

code:
frag.children.count
=> 1
frag.children.first
=> #([b]Element[/b]:0x4adc6f0 {
  name = "foo",
  children = [
    #(Element:0x22c21d8 { name = "name", children = [ #(Text "My Foo")] }),
    #(Element:0x4afa290 {
      name = "bar",
      children = [ #(Element:0x4b04e48 { name = "name", children = [ #(Text "My Foo's Bar")] })]
      })]
  })
frag.children.first.elements.count
#=> 2
Is there a good reason that frag.element_children returns an empty array? I can manipulate children instead of element_children, but the latter is more specific, and helps me avoid the superfluous child nodes that sometimes occur. I could also just do my work with full XML document objects, and look for a good way to cast them to fragments before returning them. But if I'm doing something fundamentally wrong here (either with my understanding of XML or with my use of Nokogiri), I'd like to know that and change my approach, rather than find some hack that just makes things work for now.

Edit:
Wow, frag's first child node even knows it's an element:
code:
frag.children.first.element?
=> true
frag.element_children
=> []

Peristalsis fucked around with this message at 16:17 on Oct 6, 2015

logical-fallacy
Nov 17, 2009
sudo make me a sandwich

Peristalsis posted:

Is anyone here good with Nokogiri?

I'm having an issue using XML DocumentFragments.

I'm having a bit of trouble replicating your results:

code:
> xml_string = "<foo><name>My Foo</name><bar><name>My Foo's Bar</name></bar></foo>"
=> "<foo><name>My Foo</name><bar><name>My Foo's Bar</name></bar></foo>"

> Nokogiri::XML::DocumentFragment.parse(xml_string)
=> #(DocumentFragment:0x3fec2586f208 {
  name = "#document-fragment",
  children = [
    #(Element:0x3fec2586ee84 {
      name = "foo",
      children = [
        #(Element:0x3fec258a3d78 { name = "name", children = [ #(Text "My Foo")] }),
        #(Element:0x3fec25897c80 { name = "bar", children = [ #(Element:0x3fec25892eec { name = "name", children = [ #(Text "My Foo's Bar")] })] })]
      })]
  })
  
> frag.children.count
=> 1

> frag.elements.count
=> 1

> frag.element_children.count
=> 1
What version of nokogiri/ruby are you running? I'm on ruby 2.2.3p173 with nokogiri 1.6.6.2. Have you changed any of the nokogiri settings from their defaults?

Peristalsis
Apr 5, 2004
Move along.

logical-fallacy posted:

I'm having a bit of trouble replicating your results:

code:
> xml_string = "<foo><name>My Foo</name><bar><name>My Foo's Bar</name></bar></foo>"
=> "<foo><name>My Foo</name><bar><name>My Foo's Bar</name></bar></foo>"

> Nokogiri::XML::DocumentFragment.parse(xml_string)
=> #(DocumentFragment:0x3fec2586f208 {
  name = "#document-fragment",
  children = [
    #(Element:0x3fec2586ee84 {
      name = "foo",
      children = [
        #(Element:0x3fec258a3d78 { name = "name", children = [ #(Text "My Foo")] }),
        #(Element:0x3fec25897c80 { name = "bar", children = [ #(Element:0x3fec25892eec { name = "name", children = [ #(Text "My Foo's Bar")] })] })]
      })]
  })
  
> frag.children.count
=> 1

> frag.elements.count
=> 1

> frag.element_children.count
=> 1
What version of nokogiri/ruby are you running? I'm on ruby 2.2.3p173 with nokogiri 1.6.6.2. Have you changed any of the nokogiri settings from their defaults?

Weird.

I'm using the following versions:
Ruby: 2.1.1p76
Rails: 3.2.15
Nokogiri: 1.6.3.1

I haven't deliberately changed any Nokogiri settings. I guess I should try updating Nokogiri.

Edit:
Yep, bundle update nokogiri did the trick.

Peristalsis fucked around with this message at 16:50 on Oct 7, 2015

logical-fallacy
Nov 17, 2009
sudo make me a sandwich

Peristalsis posted:

One of the .html.erb files I'm modifying has a couple of comments with extra dashes in the delimiters: <!--- comment here --->.

The ERB tmLanguage bundle is embedding text.html.basic in its definition so it looks like this behavior is defined in the standard HTML tmLanguage bundle.

It looks like having two dashes in a row that are not a part of the comment start or comment end delimiter is technically against the HTML spec. I never realized it was so stringent, never run into any problems from that myself before.

Adbot
ADBOT LOVES YOU

Peristalsis
Apr 5, 2004
Move along.

logical-fallacy posted:

The ERB tmLanguage bundle is embedding text.html.basic in its definition so it looks like this behavior is defined in the standard HTML tmLanguage bundle.

I'm not sure what you're saying here.

In any case, I just changed the triple-dashes to double-dashes, and I don't think it caused any problems.

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