Search Results

Search found 406 results on 17 pages for 'dry'.

Page 14/17 | < Previous Page | 10 11 12 13 14 15 16 17  | Next Page >

  • Recommended approach to port to ASP.NET MVC

    - by tshao
    I think many of us used to face the same question, what's the best practices to port existing web forms App to MVC. The situation for me is that we'll support both web forms and MVC at the same time. It means, we create new features in MVC, while maintaining legacy pages in web forms, and they're all in a same project. The point is: we want to keep the DRY (do not repeat yourself) principle and reduce duplicate code as much as possible. The ASPX page is not a problem as we only create new features in MVC, but there're still some shared components we want to re-use the both new / legacy pages: Master page UserControl The question here is: Is that possible to create a common master page / usercontrol that could be used in both web forms and MVC? I know that ViewMasterPage inherits from MasterPage and ViewUserControl inherits from UserControl, so it's maybe OK to let both web forms and MVC ASPX page refer to the MVC version. I did some testing and found sometimes it generates errors during the rendering of usercontrols. Any idea / experience you can share with me? Very appreciate to it.

    Read the article

  • In Java it seems Public constructors are always a bad coding practice

    - by Adam Gent
    This maybe a controversial question and may not be suited for this forum (so I will not be insulted if you choose to close this question). It seems given the current capabilities of Java there is no reason to make constructors public ... ever. Friendly, private, protected are OK but public no. It seems that its almost always a better idea to provide a public static method for creating objects. Every Java Bean serialization technology (JAXB, Jackson, Spring etc...) can call a protected or private no-arg constructor. My questions are: I have never seen this practice decreed or written down anywhere? Maybe Bloch mentions it but I don't own is book. Is there a use case other than perhaps not being super DRY that I missed? EDIT: I explain why static methods are better. .1. For one you get better type inference. For example See Guava's http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained .2. As a designer of the class you can later change what is returned with a static method. .3. Dealing with constructor inheritance is painful especially if you have to pre-calculate something.

    Read the article

  • Rails: creating a custom data type, to use with generator classes and a bunch of questions related t

    - by Shyam
    Hi, After being productive with Rails for some weeks, I learned some tricks and got some experience with the framework. About 10 days ago, I figured out it is possible to build a custom data type for migrations by adding some code in the Table definition. Also, after learning a bit about floating points (and how evil they are) vs integers, the money gem and other possible solutions, I decided I didn't WANT to use the money gem, but instead try to learn more about programming and finding a solution myself. Some suggestions said that I should be using integers, one for the whole numbers and one for the cents. When playing in script/console, I discovered how easy it is to work with calculations and arrays. But, I am talking to much (and the reason I am, is to give some sufficient background). Right now, while playing with the scaffold generator (yes, I use it, because I like they way I can quickly set up a prototype while I am still researching my objectives), I like to use a DRY method. In my opinion, I should build a custom "object", that can hold two variables (Fixnum), one for the whole, one for the cents. In my big dream, I would be able to do the following: script/generate scaffold Cake name:string description:text cost:mycustom Where mycustom should create two integer columns (one for wholes, one for cents). Right now I could do this by doing: script/generate scaffold Cake name:string description:text cost_w:integer cost_c:integer I had also had an idea that would be creating a "cost model", which would hold two columns of integers and create a cost_id column to my scaffold. But wouldn't that be an extra table that would cause some kind of performance penalty? And wouldn't that be defy the purpose of the Cake model in the first place, because the costs are an attribute of individual Cake entries? The reason why I would want to have such a functionality because I am thinking of having multiple "costs" inside my rails application. Thank you for your feedback, comments and answers! I hope my message got through as understandable, my apologies for incorrect grammar or weird sentences as English is not my native language.

    Read the article

  • DRYing up Rails Views with Nested Resources

    - by viatropos
    What is your solution to the problem if you have a model that is both not-nested and nested, such as products: a "Product" can belong_to say an "Event", and a Product can also just be independent. This means I can have routes like this: map.resources :products # /products map.resources :events do |event| event.resources :products # /events/1/products end How do you handle that in your views properly? Note: this is for an admin panel. I want to be able to have a "Create Event" page, with a side panel for creating tickets (Product), forms, and checking who's rsvp'd. So you'd click on the "Event Tickets" side panel button, and it'd take you to /events/my-new-event/tickets. But there's also a root "Products" tab for the admin panel, which could list tickets and other random products. The 'tickets' and 'products' views look 90% the same, but the tickets will have some info about the event it belongs to. It seems like I'd have to have views like this: products/index.haml products/show.haml events/products/index.haml events/products/show.haml But that doesn't seem DRY. Or I could have conditionals checking to see if the product had an Event (@product.event.nil?), but then the views would be hard to understand. How do you deal with these situations? Thanks so much.

    Read the article

  • What is an elegant way to solve this max and min problem in Ruby or Python?

    - by ????
    The following can be done by step by step, somewhat clumsy way, but I wonder if there are elegant method to do it. There is a page: http://www.mariowiki.com/Mario_Kart_Wii, where there are 2 tables... there is Mario - 6 2 2 3 - - Luigi 2 6 - - - - - Diddy Kong - - 3 - 3 - 5 [...] The name "Mario", etc are the Mario Kart Wii character names. The numbers are for bonus points for: Speed Weight Acceleration Handling Drift Off-Road Mini-Turbo and then there is table 2 Standard Bike S 39 21 51 51 54 43 48 Out Bullet Bike 53 24 32 35 67 29 67 In Bubble Bike / Jet Bubble 48 27 40 40 45 35 37 In [...] These are also the characteristics for the Bike or Kart. I wonder what's the most elegant solution for finding all the maximum combinations of Speed, Weight, Acceleration, etc, and also for the minimum, either by directly using the HTML on that page or copy and pasting the numbers into a text file. Actually, in that character table, Mario to Bower Jr are all medium characters, Baby Mario to Dry Bones are small characters, and the rest are all big characters, except the small, medium, or large Mii are just as what the name says. Small characters can only ride small bike or small kart, and so forth for medium and large.

    Read the article

  • How to use named_scope to incrementally construct a complex query?

    - by wbharding
    I want to use Rails named_scope to incrementally build complex queries that are returned from external methods. I believe I can get the behavior I want with anonymous scopes like so: def filter_turkeys Farm.scoped(:conditions => {:animal => 'turkey'}) end def filter_tasty Farm.scoped(:conditions => {:tasty => true}) end turkeys = filter_turkeys is_tasty = filter_tasty tasty_turkeys = filter_turkeys.filter_tasty But say that I already have a named_scope that does what these anonymous scopes do, can I just use that, rather than having to declare anonymous scopes? Obviously one solution would be to pass my growing query to each of the filter methods, a la def filter_turkey(existing_query) existing_query.turkey # turkey is a named_scoped that filters for turkey end But that feels like an un-DRY way to solve the problem. Oh, and if you're wondering why I would want to return named_scope pieces from methods, rather than just build all the named scopes I need and concatenate them together, it's because my queries are too complex to be nicely handled with named_scopes themselves, and the queries get used in multiple places, so I don't want to manually build the same big hairy concatenation multiple times.

    Read the article

  • Is Google Mock a good mocking framework ?

    - by des4maisons
    I am pioneering unit testing efforts at my company, and need need to choose a mocking framework to use. I have never used a mocking framework before. We have already chosen Google Test, so using Google Mock would be nice. However, my initial impressions after looking at Google Mock's tutorial are: The need for re-declaring each method in the mocking class with a MOCK_METHODn macro seems unnecessary and seems to go against the DRY principle. Their matchers (eg, the '_' in EXPECT_CALL(turtle, Forward(_));) and the order of matching seem almost too powerful. Like, it would be easy to say something you don't mean, and miss bugs that way. I have high confidence in google's developers, and low confidence in my own ability to judge mocking frameworks, never having used them before. So my question is: Are these valid concerns? Or is there no better way to define a mock object, and are the matchers intuitive to use in practice? I would appreciate answers from anyone who has used Google Mock before, and comparisons to other C++ frameworks would be helpful.

    Read the article

  • Problem creating a custom input element using FluentHtml (MVCContrib)

    - by seth
    Hi there, I just recently started dabbling in ASP.NET MVC 1.0 and came across the wonderful MVCContrib. I had originally gone down the path of creating some extended html helpers, but after finding FluentHTML decided to try my hand at creating a custom input element. Basically I am wanting to ultimately create several custom input elements to make it easier for some other devs on the project I'm working on to add their input fields to the page and have all of my preferred markup to render for them. So, in short, I'd like to wrap certain input elements with additional markup.. A TextBox would be wrapped in an <li /> for example. I've created my custom input elements following Tim Scott's answer in another question on here: DRY in the MVC View. So, to further elaborate, I've created my class, "TextBoxListItem": public class TextBoxListItem : TextInput<TextBox> { public TextBoxListItem (string name) : base(HtmlInputType.Text, name) { } public TextBoxListItem (string name, MemberExpression forMember, IEnumerable<IBehaviorMarker> behaviors) : base(HtmlInputType.Text, name, forMember, behaviors) { } public override string ToString() { var liBuilder = new TagBuilder(HtmlTag.ListItem); liBuilder.InnerHtml = ToString(); return liBuilder.ToString(TagRenderMode.SelfClosing); } } I've also added it to my ViewModelContainerExtensions class: public static TextBox TextBoxListItem<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class { return new TextBoxListItem(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors) .Value(expression.GetValueFrom(view.ViewModel)); } And lastly, I've added it to ViewDataContainerExtensions as well: public static TextBox TextBoxListItem(this IViewDataContainer view, string name) { return new TextBox(name).Value(view.ViewData.Eval(name)); } I'm calling it in my view like so: <%= this.TextBoxListItem("username").Label("Username:") %> Anyway, I'm not getting anything other than the standard FluentHTML TextBox, not wrapped in <li></li> elements. What am I missing here? Thanks very much for any assistance.

    Read the article

  • Is there really such a thing as "being good at math"?

    - by thezhaba
    Aside from gifted individuals able to perform complex calculations in their head, I'm wondering if proficiency in mathematics, namely calculus and algebra, has really got to do with one's natural inclination towards sciences, if you can put it that way. A number of students in my calculus course pick up material in seemingly no time whereas I, personally, have to spend time thinking about and understanding most concepts. Even then, if a question that requires a bit more 'imagination' comes up I don't always recognize the concepts behind it, as is the case with calculus proofs, for instance. Nevertheless, I refuse to believe that I'm simply not made for it. I do very well in programming and software engineering courses where a lot of students struggle. At first I could not grasp what they found to be so difficult, but eventually I realized that having previous programming experience is a great asset -- once I've seen and made practical use of the programming concepts learning about them in depth in an academic setting became much easier as I have then already seen their use "in the wild". I suppose I'm hoping that something similar happens with mathematics -- perhaps once the practical idea behind a concept (which authors of textbooks sure do a great job of concealing..) is evident, understanding the seemingly dry and symbolic ideas and proofs would be more obvious? I'm really not sure. All I'm sure of is I'd like to get better at calculus, but I don't yet understand why some of us pick it up easily while others have to spend considerable amounts of time on it and still not have complete understanding if an unusual problem is given.

    Read the article

  • Initialize child models at model creation

    - by Antoine
    I have a model Entree which belongs to a model Vin, which itself belongs to a model Producteur. On the form for Entree creation/edition, I want to allow the user to define the attributes for parent Vin and Producteur to create them, or retrieve them if they exist (retrieval based on user input). For now I do the following in Entree new and edit actions: @entree = Entree.new @entree.vin = Vin.new @entree.vin.producteur = Producteur.new and use fields_for helper in the form,and that works. But I intend to have much more dependencies with more models, so I want to keep it DRY. I defined a after_initialize callback in Vin model which does the producteur initialization: class Vin < ActiveRecord::Base after_initialize :vin_setup def vin_setup producteur = Producteur.new end end and remove the producteur.new from the controller. However, get an error on new action: undefined method `model_name' for NilClass:Class for the line in the form that says <%= fields_for @entree.vin.producteur do |producteur| %> I guess that means the after_initialize callback doesn't act as I expect it. Is there something I'm missing? Also, I get the same error if I define a after_initialize method in the Vin model instead of definiing a callback.

    Read the article

  • WPF binding to a boolean on a control

    - by Jose
    I'm wondering if someone has a simple succinct solution to binding to a dependency property that needs to be the converse of the property. Here's an example I have a textbox that is disabled based on a property in the datacontext e.g.: <TextBox IsEnabled={Binding CanEdit} Text={Binding MyText}/> The requirement changes and I want to make it ReadOnly instead of disabled, so without changing my ViewModel I could do this: In the UserControl resources: <UserControl.Resources> <m:NotConverter x:Key="NotConverter"/> </UserControl.Resources> And then change the TextBox to: <TextBox IsReadOnly={Binding CanEdit,Converter={StaticResource NotConverter}} Text={Binding MyText}/> Which I personally think is EXTREMELY verbose I would love to be able to just do this(notice the !): <TextBox IsReadOnly={Binding !CanEdit} Text={Binding MyText}/> But alas, that is not an option that I know of. I can think of two options. Create an attached property IsNotReadOnly to FrameworkElement(?) and bind to that property If I change my ViewModel then I could add a property CanEdit and another CannotEdit which I would be kind of embarrassed of because I believe it adds an irrelevant property to a class, which I don't think is a good practice. The main reason for the question is that in my project the above isn't just for one control, so trying to keep my project as DRY as possible and readable I am throwing this out to anyone feeling my pain and has come up with a solution :)

    Read the article

  • Invoking code both before and after WebControl.Render method

    - by Dirk
    I have a set of custom ASP.NET server controls, most of which derive from CompositeControl. I want to implement a uniform look for "required" fields across all control types by wrapping each control in a specific piece of HTML/CSS markup. For example: <div class="requiredInputContainer"> ...custom control markup... </div> I'd love to abstract this behavior in such a way as to avoid having to do something ugly like this in every custom control, present and future: public class MyServerControl : TextBox, IRequirableField { public IRequirableField.IsRequired {get;set;} protected override void Render(HtmlTextWriter writer){ RequiredFieldHelper.RenderBeginTag(this, writer) //render custom control markup RequiredFieldHelper.RenderEndTag(this, writer) } } public static class RequiredFieldHelper{ public static void RenderBeginTag(IRequirableField field, HtmlTextWriter writer){ //check field.IsRequired, render based on its values } public static void RenderEndTag(IRequirableField field, HtmlTextWriter writer){ //check field.IsRequired , render based on its values } } If I was deriving all of my custom controls from the same base class, I could conceivably use Template Method to enforce the before/after behavior;but I have several base classes and I'd rather not end up with really a convoluted class hierarchy anyway. It feels like I should be able to design something more elegant (i.e. adheres to DRY and OCP) by leveraging the functional aspects of C#, but I'm drawing a blank.

    Read the article

  • How can I send GET data to multiple URLs at the same time using cURL?

    - by Rob
    My apologies, I've actually asked this question multiple times, but never quite understood the answers. Here is my current code: while($resultSet = mysql_fetch_array($SQL)){ $ch = curl_init($resultSet['url'] . $fullcurl); //load the urls and send GET data curl_setopt($ch, CURLOPT_TIMEOUT, 2); //Only load it for two seconds (Long enough to send the data) curl_exec($ch); //Execute the cURL curl_close($ch); //Close it off } //end while loop What I'm doing here, is taking URLs from a MySQL Database ($resultSet['url']), appending some extra variables to it, just some GET data ($fullcurl), and simply requesting the pages. This starts the script running on those pages, and that's all that this script needs to do, is start those scripts. It doesn't need to return any output. Just the load the page long enough for the script to start. However, currently it's loading each URL (currently 11) one at a time. I need to load all of them simultaneously. I understand I need to use curl_multi_*, but I haven't the slightest idea on how cURL functions work, so I don't know how to change my code to use curl_multi_* in a while loop. So my questions are: How can I change this code to load all of the URLs simultaneously? Please explain it and not just give me code. I want to know what each individual function does exactly. Will curl_multi_exec even work in a while loop, since the while loop is just sending each row one at a time? And of course, any references, guides, tutorials about cURL functions would be nice, as well. Preferably not so much from php.net, as while it does a good job of giving me the syntax, its just a little dry and not so good with the explanations.

    Read the article

  • How can I abstract out the core functionality of several Rails applications?

    - by hornairs
    I'd like to develop a number of non-trivial Rails applications which all implement a core set of functionality but each have certain particular customizations, extensions, and aesthetic differences. How can I pull the core functionality (models, controllers, helpers, support classes, tests) common to all these systems out in such a way that updating the core will benefit every application based upon it? I've seen Rails Engines but they seem to be too detached, almost too abstracted to be built upon. I can seem them being useful for adding one component to an existing app, for example bolting on a blog engine to your existing e-commerce site. Since engines seem to be mostly self contained, it seems difficult and inconvenient to override their functionality and views while keeping DRY. I've also considered abstracting the code into a gem, but this seems a little odd. Do I make the gem depend on the Rails gems, and the define models & controllers inside it, and then subclass them in my various applications? Or do I define many modules inside the gem that I include in the different spots inside my various applications? How do I test the gem and then test the set of customizations and overridden functionality on top of it? I'm also concerned with how I'll develop the gem and the Rails apps in tandem, can I vendor a git repository of the gem into the app and push from that so I don't have to build a new gem every iteration? Also, are there private gem hosts/can I set my own gem source up? Also, any general suggestions for this kind of undertaking? Abstraction paradigms to adhere to? Required reading? Comments from the wise who have done this before? Thanks!

    Read the article

  • In Django, how to define a "location path" in order to display it to the users?

    - by naw
    I want to put a "location path" in my pages showing where the user is. Supposing that the user is watching one product, it could be Index > Products > ProductName where each word is also a link to other pages. I was thinking on passing to the template a variable with the path like [(_('Index'), 'index_url_name'), (_('Products'), 'products_list_url_name'), (_('ProductName'), 'product_url_name')] But then I wonder where and how would you define the hierarchy without repeating myself (DRY)? As far I know I have seen two options To define the hierarchy in the urlconf. It could be a good place since the URL hierarchy should be similar to the "location path", but I will end repeating fragments of the paths. To write a context processor that guesses the location path from the url and includes the variable in the context. But this would imply to maintain a independient hierarchy wich will need to be kept in sync with the urls everytime I modify them. Also, I'm not sure about how to handle the urls that require parameters. Do you have any tip or advice about this? Is there any canonical way to do this?

    Read the article

  • Is there a way to check if a div has the same class as an ancestor in jQuery?

    - by T.R.
    I'm looking to dynamically highlight a tab, if it represents the current page. I have: <style> #tabs li{bg-color: white;} body.Page1 #tabs .Page1, body.Page2 #tabs .Page2, body.Page3 #tabs .Page3{bg-color: orange;} </style> <body class="Page1 ADifferentClass"> <ul id="tabs"> <li class="Page1 SomeClass"> <li class="Page2 SomeOtherClass"> <li class="Page3 AnotherClass"> </ul> </body> As you can see, there needs to be CSS for each tab, so adding another page involves modifying both the HTML and the CSS. Is there a simple (DRY) way to check if two divs have the same class already built into jQuery? I ultimately went with this: <script> $(document).ready(function(){ var classRE = /Page\d+/i; var pageType = $('body').attr('className').match(classRE); $('li.'+pageType).addClass('Highlight'); }); </script> <style> #tabs li{bg-color: white;} #tabs li.Highlight{bg-color: orange;} </style>

    Read the article

  • Why does mobile first responsive design tend to not use max-width queries alongside the min-width queries?

    - by Sam
    First off, I understand the basic principles behind mobile first responsive web design, and totally agree with them. But one thing I don't understand: In my experience, not all styles for small screens can be used for the larger version of a website. For example, usually smaller versions tend to have larger clickable areas, hamburger navigation, etc. So I sometimes have to override these specific styles, aside from just progressively enhancing the base styles. So I was wondering: why is max-width rarely mentioned (or used) in the context of mobile-first responsive web design? Because it looks like it could be used to isolate styles for smaller screens that are not useful for larger screens, and would thus prevent unnecessary duplication of code. A quote which mentions min-width as typically mobile-first, but not max-width: Mobile first, from a coding perspective, means that your base style is typically a single-column, fully-fluid layout. You use @media (min-width: whatever) to add a grid-based layout on top of that. from: http://gomakethings.com/mobile-first-and-internet-explorer/ EDIT: So to be more specific: I was wondering if there is a reason to exclude max-width from a mobile-first responsive design (as it seems like it can be useful for writing your css as DRY as possible, as some styles for small screens will not be used for bigger screens).

    Read the article

  • OOP/MVC advice on where to place a global helper function

    - by franko75
    Hi, I have a couple of controllers on my site which are handling form data. The forms use AJAX and I have quite a few methods across different controllers which are having to do some specific processing to return errors in a JSON encoded format - see code below. Obviously this isn't DRY and I need to move this code into a single helper function which I can use globally, but I'm wondering where this should actually go! Should I create a static helper class which contains this function (e.g Validation::build_ajax_errors()), or as this code is producing a format which is application specific and tied into the jQuery validation plugin I'm using, should it be a static method stored in, for example, my main Website controller which the form handling controllers extend from? //if ajax request, output errors if (request::is_ajax()) { //need to build errors into array form for javascript validation - move this into a helper method accessible globally $errors = $post->errors('form_data/form_error_messages'); $i = 0; $new_errors = array(); foreach ($errors as $key => $value) { $new_errors[$i][0] = '#' . $key; $new_errors[$i][1] = $value; $new_errors[$i][2] = "error"; $i++; } echo '{"jsonValidateReturn":' . json_encode($new_errors) . '}'; return; }

    Read the article

  • Doesn't (didn't) Scala have automatically generated setters?

    - by Malvolio
    Google and my failing memory are both giving me hints that it does, but every attempt is coming up dry. class Y { var y = 0 } var m = new Y() m.y_(3) error: value y_ is not a member of Y Please tell me I am doing something wrong. (Also: please tell me what it is I am doing wrong.) EDIT The thing I am not doing wrong, or at least not the only thing I am doing wrong, is the way I am invoking the setter. The following things also fail, all with the same error message: m.y_ // should be a function valued expression m.y_ = (3) // suggested by Google and by Mchl f(m.y_) // where f takes Int => Unit as an argument f(m.y) // complains that I am passing in Int not a function I am doing this all through SimplyScala, because I'm too lazy and impatient to set up Scala on my tiny home machine. Hope it isn't that... And the winner is ... Fabian, who pointed out that I can't have a space between the _ and the =. I thought out why this should be and then it occurred to me: The name of the setter for y is not y_, it is y_= ! Observe: class Y { var y = 0 } var m = new Y() m.y_=(3) m.y res1: Int = 3 m.y_= error: missing arguments for method y_= in class Y; follow this method with `_` if you want to treat it as a partially applied function m.y_= ^ m.y_=_ res2: (Int) => Unit = def four(f : Int => Unit) = f(4) four(m.y_=) m.y res3: Int = 4 Another successful day on StackExchange.

    Read the article

  • How do I execute queries upon DB connection in Rails?

    - by sycobuny
    I have certain initializing functions that I use to set up audit logging on the DB server side (ie, not rails) in PostgreSQL. At least one has to be issued (setting the current user) before inserting data into or updating any of the audited tables, or else the whole query will fail spectacularly. I can easily call these every time before running any save operation in the code, but DRY makes me think I should have the code repeated in as few places as possible, particularly since this diverges greatly from the ideal of database agnosticism. Currently I'm attempting to override ActiveRecord::Base.establish_connection in an initializer to set it up so that the queries are run as soon as I connect automatically, but it doesn't behave as I expect it to. Here is the code in the initializer: class ActiveRecord::Base # extend the class methods, not the instance methods class << self alias :old_establish_connection :establish_connection # hide the default def establish_connection(*args) ret = old_establish_connection(*args) # call the default # set up necessary session variables for audit logging # call these after calling default, to make sure conn is established 1st db = self.class.connection db.execute("SELECT SV.set('current_user', 'test@localhost')") db.execute("SELECT SV.set('audit_notes', NULL)") # end "empty variable" err ret # return the default's original value end end end puts "Loaded custom establish_connection into ActiveRecord::Base" sycobuny:~/rails$ ruby script/server = Booting WEBrick = Rails 2.3.5 application starting on http://0.0.0.0:3000 Loaded custom establish_connection into ActiveRecord::Base This doesn't give me any errors, and unfortunately I can't check what the method looks like internally (I was using ActiveRecord::Base.method(:establish_connection), but apparently that creates a new Method object each time it's called, which is seemingly worthless cause I can't check object_id for any worthwhile information and I also can't reverse the compilation). However, the code never seems to get called, because any attempt to run a save or an update on a database object fails as I predicted earlier. If this isn't a proper way to execute code immediately on connection to the database, then what is?

    Read the article

  • How to make ActiveRecord work with legacy partitioned/sharded databases/tables?

    - by Utensil
    thanks for your time first...after all the searching on google, github and here, and got more confused about the big words(partition/shard/fedorate),I figure that I have to describe the specific problem I met and ask around. My company's databases deals with massive users and orders, so we split databases and tables in various ways, some are described below: way database and table name shard by (maybe it's should be called partitioned by?) YZ.X db_YZ.tb_X order serial number last three digits YYYYMMDD. db_YYYYMMDD.tb date YYYYMM.DD db_YYYYMM.tb_ DD date too The basic concept is that databases and tables are seperated acording to a field(not nessissarily the primary key), and there are too many databases and too many tables, so that writing or magically generate one database.yml config for each database and one model for each table isn't possible or at least not the best solution. I looked into drnic's magic solutions, and datafabric, and even the source code of active record, maybe I could use ERB to generate database.yml and do database connection in around filter, and maybe I could use named_scope to dynamically decide the table name for find, but update/create opertions are bounded to "self.class.quoted_table_name" so that I couldn't easily get my problem solved. And even I could generate one model for each table, because its amount is up to 30 most. But this is just not DRY! What I need is a clean solution like the following DSL: class Order < ActiveRecord::Base shard_by :order_serialno do |key| [get_db_config_by(key), #because some or all of the databaes might share the same machine in a regular way or can be configed by a hash of regex, and it can also be a const get_db_name_by(key), get_tb_name_by(key), ] end end Can anybody enlight me? Any help would be greatly appreciated~~~~

    Read the article

  • Create an Oracle function that returns a table

    - by Craig
    I'm trying to create a function in package that returns a table. I hope to call the function once in the package, but be able to re-use its data mulitple times. While I know I create temp tables in Oracle, I was hoping to keep things DRY. So far, this is what I have: Header: CREATE OR REPLACE PACKAGE TEST AS TYPE MEASURE_RECORD IS RECORD ( L4_ID VARCHAR2(50), L6_ID VARCHAR2(50), L8_ID VARCHAR2(50), YEAR NUMBER, PERIOD NUMBER, VALUE NUMBER ); TYPE MEASURE_TABLE IS TABLE OF MEASURE_RECORD; FUNCTION GET_UPS( TIMESPAN_IN IN VARCHAR2 DEFAULT 'MONTLHY', STARTING_DATE_IN DATE, ENDING_DATE_IN DATE ) RETURN MEASURE_TABLE; END TEST; Body: CREATE OR REPLACE PACKAGE BODY TEST AS FUNCTION GET_UPS ( TIMESPAN_IN IN VARCHAR2 DEFAULT 'MONTLHY', STARTING_DATE_IN DATE, ENDING_DATE_IN DATE ) RETURN MEASURE_TABLE IS T MEASURE_TABLE; BEGIN SELECT ... INTO T FROM ... ; RETURN T; END GET_UPS; END TEST; The header compiles, the body does not. One error message is 'not enough values', which probably means that I should be selecting into the MEASURE_RECORD, rather than the MEASURE_TABLE. What am I missing?

    Read the article

  • [SOLVED]Django - Passing variables to template based on db

    - by George 'Griffin
    I am trying to add a feature to my app that would allow me to enable/disable the "Call Me" button based on whether or not I am at [home|the office]. I created a model in the database called setting, it looks like this: class setting(models.Model): key = models.CharField(max_length=200) value = models.CharField(max_length=200) Pretty simple. There is currently one row, available, the value of it is the string True. I want to be able to transparently pass variables to the templates like this: {% if available %} <!-- Display button --> {% else %} <!-- Display grayed out button --> {% endif %} Now, I could add logic to every view that would check the database, and pass the variable to the template, but I am trying to stay DRY. What is the best way to do this? UPDATE I created a context processor, and added it's path to the TEMPLATE_CONTEXT_PROCESSORS, but it is not being passed to the template def available(request): available = Setting.objects.get(key="available") if open.value == "True": return {"available":True} else: return {} UPDATE TWO If you are using the shortcut render_to_response, you need to pass an instance of RequestContext to the function. from the django documentation: If you're using Django's render_to_response() shortcut to populate a template with the contents of a dictionary, your template will be passed a Context instance by default (not a RequestContext). To use a RequestContext in your template rendering, pass an optional third argument to render_to_response(): a RequestContext instance. Your code might look like this: def some_view(request): # ... return render_to_response('my_template.html', my_data_dictionary, context_instance=RequestContext(request)) Many thanks for all the help!

    Read the article

  • Is it good practise to blank out inherited functionality that will not be used?

    - by Timo Kosig
    I'm wondering if I should change the software architecture of one of my projects. I'm developing software for a project where two sides (in fact a host and a device) use shared code. That helps because shared data, e.g. enums can be stored in one central place. I'm working with what we call a "channel" to transfer data between device and host. Each channel has to be implemented on device and host side. We have different kinds of channels, ordinary ones and special channels which transfer measurement data. My current solution has the shared code in an abstract base class. From there on code is split between the two sides. As it has turned out there are a few cases when we would have shared code but we can't share it, we have to implement it on each side. The principle of DRY (don't repeat yourself) says that you shouldn't have code twice. My thought was now to concatenate the functionality of e.g. the abstract measurement channel on the device side and the host side in an abstract class with shared code. That means though that once we create an actual class for either the device or the host side for that channel we have to hide the functionality that is used by the other side. Is this an acceptable thing to do: public abstract class MeasurementChannelAbstract { protected void MethodUsedByDeviceSide() { } protected void MethodUsedByHostSide() { } } public class DeviceMeasurementChannel : MeasurementChannelAbstract { public new void MethodUsedByDeviceSide() { base.MethodUsedByDeviceSide(); } } Now, DeviceMeasurementChannel is only using the functionality for the device side from MeasurementChannelAbstract. By declaring all methods/members of MeasurementChannelAbstract protected you have to use the new keyword to enable that functionality to be accessed from the outside. Is that acceptable or are there any pitfalls, caveats, etc. that could arise later when using the code?

    Read the article

  • OOP + MVC advice on Member Controller

    - by dan727
    Hi, I am trying to follow good practices as much as possible while I'm learning using OOP in an MVC structure, so i'm turning to you guys for a bit of advice on something which is bothering me a little here. I am writing a site where I will have a number of different forms for members to fill in (mainly data about themselves), so i've decided to set up a Member controller where all of the forms relating to the member are represented as individual methods. This includes login/logout methods, as well as editing profile data etc. In addition to these methods, i also have a method to generate the member's control panel widget, which is a constant on every page on the site while the member is logged in. The only thing is, all of the other methods in this controller all have the same dependencies and form templates, so it would be great to generate all this in the constructor, but as the control_panel method does not have the same dependencies etc, I cannot use the constructor for this purpose, and instead I have to redeclare the dependencies and same template snippets in each method. This obviously isn't ideal and doesn't follow DRY principle, but I'm wondering what I should do with the control_panel method, as it is related to the member and that's why I put it in that controller in the first place. Am I just over-complicating things here and does it make sense to just move the control_panel method into a simple helper class? Here are the basic methods of the controller: class Member_Controller extends Website_Controller { public function __construct() { parent::__construct(); if (request::is_ajax()) { $this->auto_render = FALSE; // disable auto render } } public static function control_panel() { //load control panel view $panel = new View('user/control_panel'); return $panel; } public function login() { } public function register() { } public function profile() { } public function household() { } public function edit_profile() { } public function logout() { } }

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17  | Next Page >